Home > Backend Development > Golang > 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
Release: 2024-11-14 17:17:02
Original
538 people have browsed it

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
Copy after login

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 }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template