En Golang , las estructuras (o structs) nos permiten agrupar elementos de diferentes tipos en una sola unidad, lo que resulta útil para modelar entidades del mundo real. Las estructuras anónimas en Golang son estructuras temporales sin nombre que se utilizan para fines únicos, mientras que los campos anónimos permiten la incorporación de campos sin nombre.

Por ejemplo:
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)
}
Sintaxis:
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
}
Estructuras anónimas en Go
Las estructuras anónimas en Go se definen sin un nombre y son útiles para crear estructuras temporales y desechables. Aquí está el ejemplo de sintaxis y código.
Sintaxis:
variable := struct {
field1 dataType1
field2 dataType2
// Các trường bổ sung khi cần
}{value1, value2}
Por ejemplo:
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 una estructura Estudiante con una estructura personalDetails anónima dentro, que almacena el nombre y la información de registro. Luego inicialice el estudiante con valores para estos campos e imprímalos.
Campos anónimos
Los campos anónimos en Go le permiten definir campos sin nombres explícitos, solo se especifican sus tipos. Esto es útil cuando los campos siguen naturalmente al nombre del tipo.
Sintaxis
type StructName struct {
dataType1
dataType2
// Additional anonymous fields
}
Por ejemplo:
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
Aquí, los tipos de datos ( int, string, float64 ) actúan como nombres de campo, por lo que el acceso a los valores depende de los tipos.
Puntos importantes a recordar sobre los campos anónimos en Golang
1. Requisito único: no se pueden utilizar dos campos del mismo tipo en una estructura. Por ejemplo:
type InvalidStudent struct {
int
int // Error: duplicate type
}
2. Combinación de campos con nombre y anónimos: puedes combinar campos anónimos y con nombre en una estructura.
type Student struct {
id int // Named field
int // Anonymous field
}