Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to modify struct fields in golang

Tags:

struct

go

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 ?

like image 362
irom Avatar asked Nov 17 '17 18:11

irom


People also ask

How do you assign a value to a struct variable in Golang?

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.

How do you extend a structure in Golang?

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.

Which is the correct way to create an instance of struct type in GO?

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.

How do you use struct in Go?

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.


1 Answers

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.

like image 98
Adrian Avatar answered Sep 29 '22 07:09

Adrian