Specifying a function needs a reference?

I’m relatively new to strictly typed programming, and I’ve seen code like:
fmt.Scan(&name)

I understand why is it passed by reference, since we want to modify the existing variable, and not just make a copy of the value inside the function, and yet I’ve tried looking up documentation, and both:
https://golang.org/pkg/fmt/#Scan
and
https://golang.org/src/fmt/scan.go?s=2653:2699#L53
Didn’t have anything mentioned about passing the value by reference (both specify a ...interface{})


I’ve also tried experimenting with the code and doing fmt.Scan(name) and maybe it should throw an error or something, since you obviously need to pass the variable by reference, otherwise it will be lost in the void

My question is, could the documentation somehow mention that the value should be passed by reference? Maybe have it something like a ...*interface{}?


Thank you

Hey @arno,

This shows the importance of checking returned errors. What you’ve missed here is the part in the documentation where it specifies the following:

If that is less than the number of arguments, err will report why.```

So for example, if you run the following with error checking you will receive an error stating `type not a pointer: int`:

    package main

    import (
    	"fmt"
    	"log"
    )

    func main() {
    	var a int
    	_, err := fmt.Scan(a)
    	if err != nil {
    		log.Fatalln(err)
    	}
    }

However, that being said, I don't see any reason why it shouldn't be more specific in the documentation about it upfront, but with any scanning, you should always check the errors being returned.
1 Like

Thank you for your reply, I agree with you completely on using the return values of the function, however I also think that err should be checked in more unpredictable cases

Where as I think this is more intuitive that you need it by reference and not just pass the value, there is absolutely no point in doing otherwise

Funny thing is that if you check the source code for example a function such as fmt.Scanf, you can see that it’s just a wrapper around a function called fmt.Fscanf, but then if you actually check fmt.Fscanf's source code, once again you can see that it uses another function which is un-exported, called doScanf which actually has this as it’s documentation:

At the moment, it handles only pointers to basic types.```

Edit: I realize it's referring to the fact that it only handles simple pointer types and not the fact that it's saying only pointers in general, but I still find it funny that pointers are only mentioned that far down the calling stack :stuck_out_tongue:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.