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

How to Initialize String Pointers in Go Structs?

Barbara Streisand
Release: 2024-11-19 10:40:03
Original
900 people have browsed it

How to Initialize String Pointers in Go Structs?

Initializing String Pointers in Structs

Initializing a string pointer in a struct can be challenging, especially when you need the pointer to be nil when unset. The following code snippet demonstrates an attempt to initialize a struct with a default string pointer value:

type Config struct {
  Uri       *string
}

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

However, this code fails with the error:

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

This error occurs because you cannot get the address (to point) of a constant value. To resolve this issue, you can define a variable and pass its address instead. Here's how:

type Config struct {
  Uri       *string
}

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

Now, the initialization succeeds because v is a variable whose address can be obtained using the & operator. This allows you to point the Uri field to a nil value when unset or to a specific string value when set.

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