首页 > 后端开发 > Golang > 正文

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

Linda Hamilton
发布: 2024-11-14 16:00:03
原创
898 人浏览过

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中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板