Home  >  Article  >  Backend Development  >  How to Initialize a Struct with a String Pointer and Allow for Nil Values?

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

Barbara Streisand
Barbara StreisandOriginal
2024-11-14 17:17:02459browse

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.

The above is the detailed content of How to Initialize a Struct with a String Pointer and Allow for Nil Values?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn