How to embed custom types into other types in Golang?

WBOY
Release: 2024-06-02 10:54:57
Original
553 people have browsed it

Embedding custom types in Go: Define a custom type and embed it into another type. Access fields of a nested type through the name of the embedded type. Embedded types provide a flexible and extensible mechanism for creating complex data structures.

如何在 Golang 中将自定义类型嵌入其他类型?

#How to embed custom types in Go?

Introduction:
In Go, embedding allows you to use custom types as part of other types, which is useful for creating complex data structures and implementing compositions.

Syntax:

type EmbeddedType struct {
  // 嵌入的自定义类型
  CustomType
}
Copy after login

Example:
Let us consider a Person structure which has a name and an age fields, we want to embed it in another Employee structure that has department and salary fields.

Code:

// 自定义类型:Person
type Person struct {
  Name string
  Age  int
}

// 嵌入 Person 类型
type Employee struct {
  Person
  Department string
  Salary    int
}
Copy after login

Practical case:
Suppose we have a slice containing the Employee structure:

employees := []Employee{
  {
    Person: Person{
      Name: "John Doe",
      Age:  30,
    },
    Department: "Engineering",
    Salary:    50000,
  },
  // ...其他员工
}
Copy after login

We can iterate over the slice and access the Person fields:

for _, emp := range employees {
  fmt.Printf("Employee Name: %s, Age: %d\n", emp.Name, emp.Age)
}
Copy after login

Conclusion:
Embedded in Go is a powerful mechanism, It allows you to create flexible and extensible data structures. By embedding custom types into other types, you can easily create complex objects without having to manually copy or manage duplicate code.

The above is the detailed content of How to embed custom types into other types in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!