Home >Backend Development >Golang >How to Initialize String Pointers in Structs in Go?

How to Initialize String Pointers in Structs in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 17:35:02892browse

How to Initialize String Pointers in Structs in Go?

Initializing String Pointers in Structs

In Go, initializing a struct with a pointer to a string where the pointer can be nil requires careful handling. The following code snippet exemplifies the challenge:

type Config struct {
  Uri       *string
}

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

This fails with the error:

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

To resolve this, one cannot simply point to a constant string value as in the above code. Instead, a variable is needed:

type Config struct {
  Uri       *string
}

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

In this code, the variable v is created and initialized with the desired value. Then, the address of v (i.e., &v) is assigned to the Uri field of the struct. This works because the Uri field is a pointer to a string, and the address of v is of type *string.

The above is the detailed content of How to Initialize String Pointers in Structs in Go?. 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