Em Golang , estruturas (ou structs) nos permitem agrupar elementos de diferentes tipos em uma única unidade, o que é útil para modelar entidades do mundo real. Estruturas anônimas em Golang são estruturas temporárias sem nomes usadas para propósitos únicos, enquanto campos anônimos permitem a incorporação de campos sem nome.

Por exemplo:
package main
import "fmt"
// struct học sinh với cấu trúc và trường ẩn danh
type Student struct {
struct { // Cấu trúc bên trong ẩn danh cho thông tin cá nhân
name string
enrollment int
}
GPA float64 // Trường chuẩn
}
func main() {
student := Student{
struct {
name string
enrollment int
}{
name: "A",
enrollment: 12345,
},
GPA: 3.8,
}
fmt.Println("Name:", student.name)
fmt.Println("Enrollment:", student.enrollment)
fmt.Println("GPA:", student.GPA)
}
Sintaxe:
variable := struct {
field1 dataType1
field2 dataType2 # Cấu trúc ẩn danh
// Trường bổ sung khi cần
}{value1, value2}
type StructName struct {
dataType1
dataType2 # Trường ẩn danh
// Trường ẩn danh bổ sung
}
Estruturas Anônimas em Go
Estruturas anônimas em Go são definidas sem nome e são úteis para criar estruturas temporárias e descartáveis. Aqui está a sintaxe e o exemplo de código.
Sintaxe:
variable := struct {
field1 dataType1
field2 dataType2
// Các trường bổ sung khi cần
}{value1, value2}
Por exemplo:
package main
import "fmt"
// Cấu trúc sinh viên với cấu trúc bên trong ẩn danh cho thông tin cá nhân
type Student struct {
personalDetails struct { // Cấu trúc ẩn danh bên trong cho thông tin cá nhân
name string
enrollment int
}
GPA float64 // Trường chuẩn
}
func main() {
// Khởi tạo cấu trúc bên trong cho student
student := Student{
personalDetails: struct {
name string
enrollment int
}{
name: "A",
enrollment: 12345,
},
GPA: 3.8,
}
// Hiện giá trị
fmt.Println("Name:", student.personalDetails.name)
fmt.Println("Enrollment:", student.personalDetails.enrollment)
fmt.Println("GPA:", student.GPA)
}
Resultado:
Name: A
Enrollment: 12345
GPA: 3.8
Este código define uma estrutura Student com uma estrutura personalDetails anônima dentro, armazenando o nome e as informações de registro. Em seguida, inicialize o aluno com valores para esses campos e imprima-os.
Campos anônimos
Campos anônimos em Go permitem que você defina campos sem nomes explícitos, apenas seus tipos são especificados. Isso é útil quando os campos seguem naturalmente o nome do tipo.
Sintaxe
type StructName struct {
dataType1
dataType2
// Additional anonymous fields
}
Por exemplo:
package main
import "fmt"
// Cấu trúc học sinh bằng các trường ẩn danh
type Student struct {
int // Số đăng ký (trường ẩn danh)
string // Tên trường ẩn danh
float64 // GPA (trường ẩn danh)
}
func main() {
// Khởi tạo struct học sinh với các trường ẩn danh
student := Student{12345, "A", 3.8}
// Hiện giá trị
fmt.Println("Enrollment:", student.int)
fmt.Println("Name:", student.string)
fmt.Println("GPA:", student.float64)
}
Resultado:
Enrollment: 12345
Name: A
GPA: 3.8
Aqui, os tipos de dados ( int, string, float64 ) atuam como nomes de campos, portanto, o acesso aos valores depende dos tipos.
Pontos importantes a serem lembrados sobre campos anônimos em Golang
1. Requisito exclusivo: você não pode usar dois campos do mesmo tipo em uma estrutura. Por exemplo:
type InvalidStudent struct {
int
int // Error: duplicate type
}
2. Combinando campos nomeados e anônimos: Você pode combinar campos anônimos e nomeados em uma estrutura.
type Student struct {
id int // Named field
int // Anonymous field
}