GO语言结构体

Go语言的struct和C语言的很相似
简单的struct定义

package main

import "fmt"

type test struct{
  Name string
  Age  int
}

func main(){ 
  a:=test{"yc",22}
  fmt.Println(a) 
}

或者

package main

import "fmt"

type test struct{
  Name string
  Age  int
}

func main(){ 
  a:=test{
   Name:"john",
   Age: 19,
}
  fmt.Println(a) 
}

关于struct的操作

package main

import "fmt"

type test struct{
  Name string
  Age  int
}

func main(){ 
  a:=test{}
  fmt.Println(a) 
  a.Name="yc"
  a.Age =22
  fmt.Println(a) 
}

关于结构体做参数
不用指针就是值传递,加上指针就可以改变源地址,注意用了指针但是依旧用.进行调用

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,
}//get the address directely,a is ptr
   A(a)
  fmt.Println(a) 
   a.Age=20
  fmt.Println(a) 
}

可以直接取a为结构体地址,而且这样的a还兼容普通的类型操作,所以是常用情况

匿名结构

package main
import "fmt"
func main(){ 

   a:=struct{
   Name string
   Age int
   }{
    Name:"joe",
    Age:19,
   }
   fmt.Println(a)
}

嵌套结构体

package main

import "fmt"

type person struct{
   Name string
   Age int
   Contact struct{
      Phone,City string
   } 
}

func main(){ 

   a:=person{
    Name:"joe",
    Age:19,
    }
    a.Contact.Phone="123456"
    a.Contact.City="nih"
   fmt.Println(a)
}

匿名字段

package main

import "fmt"

type person struct{
   string
   int
}

func main(){ 

   a:=person{
   "joe",
    19,
    }
   fmt.Println(a)
}

注意匿名字段赋值的时候一定要按照声明次序

结构体的组合(Go语言没有继承)
嵌入

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)
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值