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)
}
CodePudding user response:
To summarize the various comments:
You can simply return an empty string instead of a pointer.
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 "", err
}
defer f.Close()
return Convert(f)
}
func main() {
dat, err := ConvertPath("/tmp/dat2")
if err != nil {
panic(err)
}
fmt.Println(dat)
}