Table of Contents
Question content
Solution
Home Backend Development Golang Structure slicing! =The interface slice it implements?

Structure slicing! =The interface slice it implements?

Feb 09, 2024 pm 01:03 PM
go language overflow

Structure slicing! =The interface slice it implements?

php editor Apple is here to reveal a puzzle about structure slicing: What is the difference between structure slicing and the interface slicing it implements? In the Go language, slices are a convenient and flexible data structure that can change size dynamically. Struct slicing is a special form of slicing, which stores elements of structure type. But how is it different from a slice that implements the same interface? Let us find out the answer together.

Question content

I have an interface Model, which is implemented by struct Person.

To get the model instance, I have the following helper function:

func newModel(c string) Model {
    switch c {
    case "person":
        return newPerson()
    }
    return nil
}

func newPerson() *Person {
    return &Person{}
}
Copy after login

The above method allows me to return a Person instance of the correct type (new models can be easily added later using the same method).

When I try to do something like this to return a model slice, I get an error. Code:

func newModels(c string) []Model {
    switch c {
    case "person":
        return newPersons()
    }
    return nil
}

func newPersons() *[]Person {
    var models []Person
    return &models
}
Copy after login

Go complains: Cannot use newPersons() (type []Person) as a return parameter of type []Model

My goal is to return a slice of whatever model type is requested (whether []Person, []FutureModel, []Terminator2000, w/ e). What am I missing and how to properly implement such a solution?

Solution

This is very similar to the question I just answered: https://www.php.cn/link/2c029952e202c0e560626a4c5980d64c

The short answer is you are right. A slice of a struct is not equal to a slice of the interface implemented by the struct.

[]Person and []Model have different memory layouts. This is because the types they belong to have different memory layouts. Model is an interface value, which means that in memory it is two words in size. One word represents type information and the other word represents data. Person is a structure whose size depends on the fields it contains. In order to convert from []Person to []Model, you need to loop through the array and typecast each element.

Since this conversion is an O(n) operation and results in the creation of a new slice, Go refuses to perform this operation implicitly. You can do this explicitly using the following code.

models := make([]Model, len(persons))
for i, v := range persons {
    models[i] = Model(v)
}
return models
Copy after login

As dskinner pointed out , you most likely need a pointer to a slice, not a pointer to a slice. Pointers to slices are generally not needed.

*[]Person        // pointer to slice
[]*Person        // slice of pointers
Copy after login

The above is the detailed content of Structure slicing! =The interface slice it implements?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

Is H5 page production a front-end development? Is H5 page production a front-end development? Apr 05, 2025 pm 11:42 PM

Yes, H5 page production is an important implementation method for front-end development, involving core technologies such as HTML, CSS and JavaScript. Developers build dynamic and powerful H5 pages by cleverly combining these technologies, such as using the <canvas> tag to draw graphics or using JavaScript to control interaction behavior.

Why are the inline-block elements misaligned? How to solve this problem? Why are the inline-block elements misaligned? How to solve this problem? Apr 04, 2025 pm 10:39 PM

Regarding the reasons and solutions for misaligned display of inline-block elements. When writing web page layout, we often encounter some seemingly strange display problems. Compare...

How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? How to use the clip-path attribute of CSS to achieve the 45-degree curve effect of segmenter? Apr 04, 2025 pm 11:45 PM

How to achieve the 45-degree curve effect of segmenter? In the process of implementing the segmenter, how to make the right border turn into a 45-degree curve when clicking the left button, and the point...

How to customize the resize symbol through CSS and make it uniform with the background color? How to customize the resize symbol through CSS and make it uniform with the background color? Apr 05, 2025 pm 02:30 PM

The method of customizing resize symbols in CSS is unified with background colors. In daily development, we often encounter situations where we need to customize user interface details, such as adjusting...

How to control the top and end of pages in browser printing settings through JavaScript or CSS? How to control the top and end of pages in browser printing settings through JavaScript or CSS? Apr 05, 2025 pm 10:39 PM

How to use JavaScript or CSS to control the top and end of the page in the browser's printing settings. In the browser's printing settings, there is an option to control whether the display is...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

See all articles