Home >Backend Development >Golang >How to Correctly Initialize Embedded Structs in Go?
Golang Embedded Struct Types: Understanding the Syntax and Usage
When working with embedded struct types in Go, it's crucial to comprehend their syntax and proper usage. This article addresses the issue of being unable to initialize an embedded struct.
Problem:
Consider the following types:
type Value interface{} type NamedValue struct { Name string Value Value } type ErrorValue struct { NamedValue Error error }
Attempting to initialize an ErrorValue using the syntax:
e := ErrorValue{Name: "alpha", Value: 123, Error: err}
results in an error.
Solution:
Embedded types, also known as unnamed fields, are referred to by their unqualified type name. In the provided code, the syntax for initializing the ErrorValue is incorrect.
As per the Go language specification, an embedded field should be initialized using the type name without a field name. Here's the correct syntax:
e := ErrorValue{NamedValue: NamedValue{Name: "fine", Value: 33}, Error: err}
Alternatively, you can omit the field names from the composite literal:
e := ErrorValue{NamedValue{"fine", 33}, err}
Example:
package main import "fmt" type Value interface{} type NamedValue struct { Name string Value Value } type ErrorValue struct { NamedValue Error error } func main() { e := ErrorValue{NamedValue{Name: "alpha", Value: 123}, fmt.Errorf("some error")} fmt.Println(e) }
Output:
{NamedValue:{Name:alpha Value:123} Error:some error}
By understanding the syntax and usage of embedded struct types, you can effectively leverage them in your Go programs.
The above is the detailed content of How to Correctly Initialize Embedded Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!