Home > Backend Development > Golang > How Do Go's Struct Setters Handle Pass-by-Value vs. Pass-by-Reference?

How Do Go's Struct Setters Handle Pass-by-Value vs. Pass-by-Reference?

Barbara Streisand
Release: 2024-12-14 14:29:15
Original
491 people have browsed it

How Do Go's Struct Setters Handle Pass-by-Value vs. Pass-by-Reference?

Understanding Struct Setters in Go

In Go, structs can be passed into functions by reference or by value. When passed by reference, the function can modify the original struct. However, passing a struct by value leads to the creation of a new copy of the struct within the function, and any modifications made to this copy will not alter the original struct.

In the provided code example:

type T struct { Val string }
Copy after login

The struct T contains a single string field named Val.

func (t T) SetVal(s string) {
    t.Val = s
}
Copy after login

The SetVal method receives a struct by value and attempts to modify its Val field. However, this does not work as expected because the function is operating on a copy of the struct.

func (t *T) SetVal2(s string) {
    (*t).Val = s
}
Copy after login

The SetVal2 method, on the other hand, receives a pointer to a struct and can therefore modify the original struct. This is because Go dynamically type-checks pointers, allowing the function to access the underlying struct and modify its fields directly.

In summary, it is essential to understand that structs passed by value create a new copy, preventing any modifications made within the function from affecting the original struct. To modify the original struct from within a function, it must be passed by reference, using a pointer.

The above is the detailed content of How Do Go's Struct Setters Handle Pass-by-Value vs. Pass-by-Reference?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template