1. x := "I am a string!"
  2. x = nil // Won't compile, strings can't be nil in Go
  1. var x *string
  2. x = nil // Compiles! String pointers in GoLang can be nil

从上面的例子,我们可以看出:

  • 除非你需要使用nil, 否则最好使用正常的字符串
  • 正常的字符串类型在golang中的使用,更简单更安全

使用指针需要我们在解引用之前做一些判断,空字符串“”和nil并不是同一个东西:

  1. func UseString(s *string) error {
  2. if s == nil {
  3. temp := "" // *string cannot be initialized
  4. s = &temp // in one statement
  5. }
  6. value := *s // safe to dereference the *string
  7. }

结构体中使用字符串

例子1

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type Config struct {
  7. Environment string
  8. Version string
  9. HostName string
  10. }
  11. func (c *Config) String() string {
  12. return fmt.Sprintf("Environment: '%v'\nVersion:'%v'\nHostName: '%v'",
  13. c.Environment, c.Version, c.HostName)
  14. }
  15. func main() {
  16. jsonDoc :=`
  17. {
  18. "Environment" : "Dev",
  19. "Version" : ""
  20. }`
  21. conf := &Config{}
  22. json.Unmarshal([]byte(jsonDoc), conf)
  23. fmt.Println(conf) // Prints
  24. // Environment: 'Dev'
  25. // Version:''
  26. // HostName: ''
  27. }

我们可以看到Version和HostName都是空字符串“”, 而且我们也可以看到,即使没有对HostName做赋值,也可以得到其默认值。问题就来了,假如说,我们规定必须要为HostName赋值,这时候就需要使用字符串指针了。

例子2

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type ConfigWithPointers struct {
  7. Environment *string // pointer to string
  8. Version *string
  9. HostName *string
  10. }
  11. func (c *ConfigWithPointers) String() string {
  12. var envOut, verOut, hostOut string
  13. envOut = "<nil>"
  14. verOut = "<nil>"
  15. hostOut = "<nil>"
  16. if c.Environment != nil { // Check for nil!
  17. envOut = *c.Environment
  18. }
  19. if c.Version != nil {
  20. verOut = *c.Version
  21. }
  22. if c.HostName != nil {
  23. hostOut = *c.HostName
  24. }
  25. return fmt.Sprintf("Environment: '%v'\nVersion:'%v'\nHostName: '%v'",
  26. envOut, verOut, hostOut)
  27. }
  28. func main() {
  29. jsonDoc :=
  30. `
  31. {
  32. "environment" : "asdf",
  33. "hostName" : ""
  34. }
  35. `
  36. conf := &ConfigWithPointers{}
  37. json.Unmarshal([]byte(jsonDoc), conf)
  38. fmt.Println(conf) // Prints the following:
  39. // Environment: 'asdf'
  40. // Version:'<nil>'
  41. // HostName: ''
  42. }