I have example play.golang.org/p/Y1KX-t5Sj9 where I define method Modify() on struct User
type User struct { Name string Age int } func (u *User) Modify() { *u = User{Name: "Paul"} }
in the main() I am defining struct literal &User{Name: "Leto", Age: 11} then call u.Modify(). That results in printing 'Paul 0' I like that struct field Name is changed , but what is the correct way to keep Age field ?
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members.
We cannot directly extend structs but rather use a concept called composition where the struct is used to form other objects. So, you can say there is No Inheritance Concept in Golang.
Struct Instantiation Using new Keyword An instance of a struct can also be created with the new keyword. It is then possible to assign data values to the data fields using dot notation.
Declaring a struct typetype <name-of-custom-type> struct { field1-Name field1-Type field2-Name field2-Type ... } In the above syntax, <name-of-custom-type> is a struct type while field1-Name and field1-Name are fields of data type field1-Type and field1-Type respectively.
Just modify the field you want to change:
func (u *User) Modify() { u.Name = "Paul" }
This is covered well in the Go tour which you should definitely read through, it doesn't take long.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With