0
Go structs in functions
Hey guys. I'm trying to learn GO so I jumped right into doing code examples in the lessons. But there is a task it seems I cannot handle by myself. It's about having a struct and have to use a function to change one of the structs values. My problem with this is that I don't know how to address the struct right in the functions definition. So any GO pros out there?
11 odpowiedzi
+ 1
You need to either pass the struct as the function argument or create a new struct in the function
+ 1
It is better to pass by reference
+ 1
If you want to change the value of the struct and use them in your program
+ 1
Passing by reference is also more efficient
+ 1
Ok
+ 1
Passing by reference means to send the memory adress as a argument, which is got by using the ampersand '&', but whenever you want yo use that struct it needs to be dereferenced with the asterix '*'
+ 1
type Teststruct struct {attribute1 int}
*p := Teststruct
testfunction (&p) {.. }
func testfunction (&p) {
(*p).attribute1 := 4
}
+ 1
You're welcome
0
Okay let's assume I have a struct like
type Teststruct struct {attribute1 int}
have a pointer used on it like
*p := Teststruct
and it should be passed to the function like
testfunction (&p) {.. }
would it be right to define it like that?
func testfunction (&p) {}
or like func testfunction (type xy struct {Val int}) {...}.?
0
Can you maybe give me an example since I'm not sure if I understand pass by reference?
0
Cool you really helped me out. Thank you very much