Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Golang trying to store the values of pointers

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading