La estructura es una colección de datos compuesta por una serie de datos del mismo tipo o de diferentes tipos.
Las matrices en el lenguaje Go pueden almacenar el mismo tipo de datos, pero en la estructura podemos definir diferentes tipos de datos para diferentes elementos.
Definición de estructura
Las definiciones de estructura necesitan usar declaraciones de tipo y estructura.
La declaración de estructura define un nuevo tipo de datos con uno o más miembros en la estructura.
La declaración de tipo establece el nombre de la estructura.
El formato de la estructura es el siguiente:
type test struct {
member definition
member definition
...
member definition
}
Una vez definido el tipo de estructura, se puede utilizar para declaraciones de variables. El formato de sintaxis es el siguiente:
variable_name := test {
value1, value2...valuen}
或
variable_name := test {
key1: value1, key2: value2..., keyn: valuen}
Ejemplo:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
// 创建一个新的结构体
fmt.Println(Books{
"Go 语言", "zhangsan", "Go 语言教程", 34324})
// 也可以使用 key => value 格式
fmt.Println(Books{
title: "Go 语言", author: "zhangsan", subject: "Go 语言教程", book_id: 878756})
// 忽略的字段为 0 或 空
fmt.Println(Books{
title: "Go 语言", author: "zhangsan"})
}
Miembro de la estructura de acceso
Si desea acceder a los miembros de la estructura, debe usar un punto. El
formato del operador es:
Estructura. Nombre del miembro
Las variables de tipo de estructura se definen mediante la palabra clave struct
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* 声明 Book1 为 Books 类型 */
var Book2 Books /* 声明 Book2 为 Books 类型 */
/* book 1 描述 */
Book1.title = "Go 语言"
Book1.author = "www.runoob.com"
Book1.subject = "Go 语言教程"
Book1.book_id = 6495407
/* book 2 描述 */
Book2.title = "Python 教程"
Book2.author = "www.runoob.com"
Book2.subject = "Python 语言教程"
Book2.book_id = 6495700
/* 打印 Book1 信息 */
fmt.Printf( "Book 1 title : %s\n", Book1.title)
fmt.Printf( "Book 1 author : %s\n", Book1.author)
fmt.Printf( "Book 1 subject : %s\n", Book1.subject)
fmt.Printf( "Book 1 book_id : %d\n", Book1.book_id)
/* 打印 Book2 信息 */
fmt.Printf( "Book 2 title : %s\n", Book2.title)
fmt.Printf( "Book 2 author : %s\n", Book2.author)
fmt.Printf( "Book 2 subject : %s\n", Book2.subject)
fmt.Printf( "Book 2 book_id : %d\n", Book2.book_id)
}
Esto es muy similar a llamar en JAVA. Después de definir el objeto, encapsulando la variable miembro, puede usar. Para llamar a la variable miembro.
Pero el lenguaje go solo admite la encapsulación y no admite la herencia ni el polimorfismo, que es diferente de JAVA.
El resultado de ejecución es:
Book 1 title : Go 语言
Book 1 author : www.runoob.com
Book 1 subject : Go 语言教程
Book 1 book_id : 6495407
Book 2 title : Python 教程
Book 2 author : www.runoob.com
Book 2 subject : Python 语言教程
Book 2 book_id : 6495700
El tipo de estructura se pasa a la función como parámetro
El puntero no se usa para pasar por valor y la dirección de origen se puede cambiar agregando el puntero.Tenga en cuenta que se usa el puntero pero el.
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books /* 声明 Book1 为 Books 类型 */
var Book2 Books /* 声明 Book2 为 Books 类型 */
/* book 1 描述 */
Book1.title = "Go 语言"
Book1.author = "www.runoob.com"
Book1.subject = "Go 语言教程"
Book1.book_id = 6495407
/* book 2 描述 */
Book2.title = "Python 教程"
Book2.author = "www.runoob.com"
Book2.subject = "Python 语言教程"
Book2.book_id = 6495700
/* 打印 Book1 信息 */
printBook(Book1)
/* 打印 Book2 信息 */
printBook(Book2)
}
func printBook( book Books ) {
fmt.Printf( "Book title : %s\n", book.title)
fmt.Printf( "Book author : %s\n", book.author)
fmt.Printf( "Book subject : %s\n", book.subject)
fmt.Printf( "Book book_id : %d\n", book.book_id)
}
Puede tomar directamente a como dirección de estructura, y también es compatible con operaciones de tipo ordinario, por lo que es una situación común
el código se muestra a continuación:
package main
import "fmt"
type test struct{
Name string
Age int
}
func A(t* test){
t.Age = 15
}
func main(){
a:=&test{
Name:"john",
Age: 19,
}
A(a)
fmt.Println(a)
a.Age=20
fmt.Println(a)
}
Puntero de estructura
La definición de un puntero a una estructura es similar a otras variables de puntero en el siguiente formato:
var struct_pointer *Books
La variable de puntero definida anteriormente puede almacenar la dirección de la variable de estructura. Para ver la dirección de la variable de estructura, el símbolo & se puede colocar antes de la variable de estructura:
struct_pointer = &Book1
Utilice punteros de estructura para acceder a los miembros de la estructura, utilice el operador ".":
struct_pointer.title
Utilice el puntero de estructura para reescribir el ejemplo anterior, el código es el siguiente:
package main
import "fmt"
type Books struct {
title string
author string
subject string
book_id int
}
func main() {
var Book1 Books
var Book2 Books
/* book 1 描述 */
Book1.title = "Go 语言"
Book1.author = "www.runoob.com"
Book1.subject = "Go 语言教程"
Book1.book_id = 6495407
/* book 2 描述 */
Book2.title = "Python 教程"
Book2.author = "www.runoob.com"
Book2.subject = "Python 语言教程"
Book2.book_id = 6495700
/* 打印 Book1 信息 */
printBook(&Book1)
/* 打印 Book2 信息 */
printBook(&Book2)
}
func printBook( book *Books ) {
fmt.Printf( "Book title : %s\n", book.title)
fmt.Printf( "Book author : %s\n", book.author)
fmt.Printf( "Book subject : %s\n", book.subject)
fmt.Printf( "Book book_id : %d\n", book.book_id)
}
El resultado de ejecución es:
Book title : Go 语言
Book author : www.runoob.com
Book subject : Go 语言教程
Book book_id : 6495407
Book title : Python 教程
Book author : www.runoob.com
Book subject : Python 语言教程
Book book_id : 6495700
Estructura anónima
package main
import "fmt"
func main(){
a:=struct{
Name string
Age int
}
{
Name:"joe",
Age:19,
}
fmt.Println(a)
}
Anidación de estructuras
package main
import "fmt"
type human struct{
Sex int
}
type teacher struct{
human
Name string
Age int
}
type student struct{
human
Name string
Age int
}
func main(){
a:=student{
Name:"joe",Age:19,human:human{
Sex:0}};
b:=teacher{
Name:"joe",Age:20,human:human{
Sex:0}};
fmt.Println(a,b)
a.Sex=1
fmt.Println(a,b)
}