2

I’m trying to implement an increment function on my struct. I’m not sure why, but it appears that when I call F.incr() in main, the fib struct’s parameters appear to remain constant. I think I may have an incorrect idea about what I’m doing in my incr() function, though I’m not able to find the right documentation. What am I missing?

type fib struct { i uint64 fa uint64 fb uint64 } func (F fib) incr(){ F.i++ F.fa, F.fb = F.fa+F.fb, F.fa } func main() { F := fib{1,1,0} var sum uint64 = 0 for; F.i <= 10; F.incr() { k := f(F.i, F.fb, F.fa) fmt.Printf("calculating the %vth f(i,F_%v, F_%v): %v\n", F.i, F.i-1, F.i, k) —snip- 

edit: thanks @peterSO, I needed to change incr to func (F *fib) incr(){

2
  • 3
    In Go, all arguments are passed by value. Pass a pointer. The documentation is The Go Programming Language Specification. For example, "the parameters of the call are passed by value to the function" golang.org/ref/spec#Calls Commented Feb 16, 2020 at 18:48
  • The code from the question does not compile, however as @peterSO wrote you need to use reference for incr() function. See here -> play.golang.org/p/g2iIXFY4y_U Commented Feb 16, 2020 at 18:52

1 Answer 1

2

You need to update your method to increase the value of the variable at the location. Hence, you need to change the F() method

func (F *fib) incr(){ F.i++ F.fa, F.fb = F.fa+F.fb, F.fa } 

The difference being the *

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.