英文:
How to create a function that can return nil or string value instead of the memory address?
问题
我的目标是创建一个能够返回nil或string值的函数。
我使用*string来允许函数返回nil或string指针。
问题是函数返回的是内存地址而不是string值。简单的解决方法是使用*。
然而,我认为这是一种不好的做法。例如,我将其与func os.Open(name string) (*os.File, error)进行比较,后者返回os.File指针,但我可以在不使用*的情况下访问变量。
最佳实践:
func main() {
  f, _ := os.Open("/tmp/dat")
  b1 := make([]byte, 5)
  f.Read(b1) // 我不需要使用*
  fmt.Println("%s", string(b1))
}
我目前的代码认为不是最佳实践:
func main() {
  dat, _ := ConvertPath("/tmp/dat2")
  fmt.Println(*dat) // 我需要使用*
}
这是剩余的代码:
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)
}
英文:
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)
}
答案1
得分: 1
总结各种评论:
你可以简单地返回一个空字符串而不是指针。
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论