Home > Backend Development > Golang > Why can't we assign a value when we return a struct instead of a pointer to a struct?

Why can't we assign a value when we return a struct instead of a pointer to a struct?

WBOY
Release: 2024-02-09 17:30:10
forward
996 people have browsed it

Why cant we assign a value when we return a struct instead of a pointer to a struct?

In C language, when we return a structure instead of a pointer to the structure, the reason why we cannot directly assign the value is that the entire structure will be copied when returning the structure content instead of returning a pointer to the structure. Since a structure may contain a large amount of data, copying the entire structure may be expensive. Therefore, in order to improve efficiency, the C language stipulates that when a structure is returned, we can only use it by assigning it to a variable of structure type. This can avoid unnecessary copy operations and improve code execution efficiency.

Question content

Suppose we have the following structure

type profile struct {
    id   int
    name string
}

func test(p profile) profile {
    return p
}

func main() {
    var profile profile
    test(profile).id = 20 // cannot assign to test(profile).id (value of type int)
}
Copy after login

But if we change the profile of the test function return type to *profile, the main function will work.

func test(p Profile) *Profile {
    return &p
}

func main() {
    var profile Profile
    test(profile).id = 20 // Works
}
Copy after login

Why is this?

Workaround

Assigning fields to Profile in this way has no noticeable effect. You are assigning a temporary struct value (of a field) and then immediately discarding it. Note that test's return value is a copy of the profile in main; it is copied into the test's parameters, and then copied again when returning from the test.

When returning a pointer, at least in principle, the structure pointed to will still be accessible after the assignment (although not in this particular case, since the pointer points to a copy of the argument being tested).

The above is the detailed content of Why can't we assign a value when we return a struct instead of a pointer to a struct?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template