首页  >  文章  >  后端开发  >  如何在 Go 结构体中初始化字符串指针?

如何在 Go 结构体中初始化字符串指针?

Linda Hamilton
Linda Hamilton原创
2024-11-14 16:00:03899浏览

How to Initialize a String Pointer in a Go Struct?

Initializing a String Pointer in a Go Struct

In Go, structs can contain pointers to other values, including strings. While it's straightforward to initialize strings directly in structs, initializing string pointers can present a challenge.

Problem

When attempting to initialize a struct with a string pointer (*string) as a default value, an error occurs:

cannot use "string" (type string) as type *string in field value

Solution

To initialize a string pointer in a struct, you can't directly assign a constant string value to it. Instead, create a variable, assign the value to it, and then pass the variable's address to the string pointer:

type Config struct {
  Uri       *string
}

func init() {
  v := "my:default"
  var config = Config{ Uri: &v }
}

By using the & operator, you obtain the address of the variable (&v), which can then be assigned to the string pointer. This enables the comparison of two struct instances where Uri can be nil if not set.

以上是如何在 Go 结构体中初始化字符串指针?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn