Home > Net >  Golang trying to store the values of pointers
Golang trying to store the values of pointers

Time:08-05

I have a problem and I'm confused about how to solve it.

I have this task:

1. Store the result of the division in the int which a points to.
2. Store the remainder of the division in the int which b points to.

My code is:

package main

import "fmt"

func Function(a *int, b *int) {
    *a = *a / *b
    *b = *a % *b
}

func main() {
    a := 13
    b := 2
    Function(&a, &b)
    fmt.Println(a)
    fmt.Println(b)
}

The output should be 6 and 1, however, I don't know how to write the code in the Function func the way it would store the results properly. How do I fix my code? Function should divide the dereferenced value of a by the dereferenced value of b.

CodePudding user response:

The function clobbers the value of *a before the value is used in the second statement. Use this code:

func Function(a *int, b *int) {
    *a, *b = *a / *b, *a % *b
}

The expressions on the right hand side of the = are evaluated before assignments to the variables on the left hand side.

Another option is to assign *a / *b to a temporary value:

func Function(a *int, b *int) {
    t := *a / *b
    *b = *a % *b
    *a = t
}
  •  Tags:  
  • go
  • Related