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?

30th Sep 2021, 11:21 AM
Stefan
Stefan - avatar
11 odpowiedzi
+ 1
You need to either pass the struct as the function argument or create a new struct in the function
30th Sep 2021, 11:30 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
It is better to pass by reference
30th Sep 2021, 11:46 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
If you want to change the value of the struct and use them in your program
30th Sep 2021, 11:47 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
Passing by reference is also more efficient
30th Sep 2021, 11:47 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
Ok
30th Sep 2021, 11:52 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 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 '*'
30th Sep 2021, 11:54 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
type Teststruct struct {attribute1 int} *p := Teststruct testfunction (&p) {.. } func testfunction (&p) { (*p).attribute1 := 4 }
30th Sep 2021, 11:55 AM
Eashan Morajkar
Eashan Morajkar - avatar
+ 1
You're welcome
30th Sep 2021, 12:02 PM
Eashan Morajkar
Eashan Morajkar - avatar
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}) {...}.?
30th Sep 2021, 11:40 AM
Stefan
Stefan - avatar
0
Can you maybe give me an example since I'm not sure if I understand pass by reference?
30th Sep 2021, 11:51 AM
Stefan
Stefan - avatar
0
Cool you really helped me out. Thank you very much
30th Sep 2021, 12:00 PM
Stefan
Stefan - avatar