How to pass struct to a function as pointer in Go

3 Answers

0 votes
package main
 
import (
    "fmt"
)
 
type S struct {
    x, y float64
}
 
func (st *S) Add(f float64) {
    st.x = st.x + f
    st.y = st.y + f
}
 
func main() {
    st := S{2, 7}
    st.Add(10)
    fmt.Println(st.x, st.y)
}
 
 
 
/*
run:
 
12 17
 
*/

 



answered Mar 17, 2020 by avibootz
edited Mar 17, 2020 by avibootz
0 votes
package main

import (
	"fmt"
)

type S struct {
	x, y float64
}

func f(st *S, f float64) {
	st.x = st.x + f
	st.y = st.y +  f
}

func main() {
	st := S{3, 8}
	f(&st, 10)
	fmt.Println(st.x, st.y)
}



/*
run:

13 18

*/

 



answered Mar 17, 2020 by avibootz
0 votes
package main
  
import (
    "fmt"
)
  
type S struct {
    x, y float64
}
  
func (st *S) Add(f float64) {
    st.x = st.x + f
    st.y = st.y + f
}
  
func main() {
    st := &S{4, 6}
    st.Add(10)
    fmt.Println(st.x, st.y)
}
  
  
  
/*
run:
  
14 16
  
*/

 



answered Mar 17, 2020 by avibootz

Related questions

1 answer 216 views
216 views asked Nov 4, 2020 by avibootz
1 answer 194 views
1 answer 207 views
1 answer 180 views
180 views asked Mar 7, 2020 by avibootz
1 answer 172 views
172 views asked Aug 24, 2020 by avibootz
2 answers 159 views
...