首頁 > 後端開發 > Golang > 主體

如何使用字串指標初始化結構並允許 Nil 值?

Barbara Streisand
發布: 2024-11-14 17:17:02
原創
462 人瀏覽過

How to Initialize a Struct with a String Pointer and Allow for Nil Values?

Struct Pointer Initialization

Initializing a struct with a string pointer can be tricky, especially when the default value should be nil.

Problem

When attempting to initialize a struct with a string pointer as a default value, using a constant string in the initialization, an error occurs:

cannot use "string" (type string) as type *string in field value
登入後複製

Solution

To initialize a struct with a string pointer that can be nil, you must assign the address of a variable, not a constant value, to the pointer. Here's a modified code that works:

type Config struct {
  Uri       *string
}

func init() {
  v := "my:default"
  var config = Config{ Uri: &v }
}
登入後複製

In this case, the variable v holds the default string value. By taking its address using the & operator and assigning it to Uri, we're creating a string pointer that can be used for comparisons and can be nil if not explicitly set.

以上是如何使用字串指標初始化結構並允許 Nil 值?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板