My goal is to create a function that can return nil or string value.
I use *string to allow a function to return nil or string pointer.
The problem is that function return memory address instead of the string value. The easy solution is to use *.
However, I believe that is a bad practice. E.g I am comparing it with func os.Open(name string) (*os.File, error) which return os.File pointer, but I can access the variable without *.
The best practice:
func main() {
f, _ := os.Open("/tmp/dat")
b1 := make([]byte, 5)
f.Read(b1) // I don't need to use *
fmt.Println("%s", string(b1))
}
My current code which I believe is not a best practice:
func main() {
dat, _ := ConvertPath("/tmp/dat2")
fmt.Println(*dat) // I need to use *
}
This is the rest of the code:
func Convert(r io.Reader) (*string, error) {
dat := "hello"
return &dat, nil
}
func ConvertPath(path string) (*string, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
return Convert(f)
}
nilor "string", the approach you chose is acceptable. Trying to implement some "optional" type would be unidiomatic.if err != nil { // do something }. isn't empty string is notnil, hence will cause panic?. Anyway, that's not the point of this question, I want to know howos.Opencan return*os.Filebut I can call it without*.(string,error), with the understanding that a non-nil error means the string is meaningless. It is also possible to return(string,bool,error)to denote the existence or non-existence of the string. Returns a*stringis also ok. With a*os.Filereturn type, the compiler inserts the redirection automatically. If you had a function that tookFile, you would've passed*f.(string,error)then if that is the idiomatic way in Go. Anyway, I can't seeossource code, so I am guessing that somewhere inos.Openfunction it return*os.File, it just happen that I can't do the same withreturn *string