How to Initialize String Pointers in Structs in Go?

Barbara Streisand
Release: 2024-11-12 17:35:02
Original
808 people have browsed it

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

This fails with the error:

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

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

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!

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