加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang struct

发布时间:2020-12-16 18:18:27 所属栏目:大数据 来源:网络整理
导读:struct 1、定义一个struct packagemainimport"fmt"typeRectanglestruct{widthfloat64heightfloat64}funcmain(){varrRectangle//声明一个结构体r,widthheight的值为“零”值。在这里为0.0,0.0r=Rectangle{width:20,height:10}//给长宽赋值,带名称时,顺序随意

struct


1、定义一个struct

packagemain

import"fmt"

typeRectanglestruct{
	widthfloat64
	heightfloat64
}

funcmain(){
	varrRectangle//声明一个结构体r,widthheight的值为“零”值。在这里为0.0,0.0
	r=Rectangle{width:20,height:10}//给长宽赋值,带名称时,顺序随意
	r=Rectangle{20,10}//等价上部的赋值,不带变量名称时,值与声明的变量顺序一致。
	fmt.Println("theRectanglewidth:",r.width)//访问r.{属性}
}
//执行结果:
theRectanglewidth:20

2、给结构体定义方法

packagemain

import"fmt"

typeRectanglestruct{
	widthfloat64
	heightfloat64
}

func(r*Rectangle)area()float64{//定义一个area的函数,返回值类型为float64,函数的接收者为前面括号的(变量名类型名)
	returnr.width*r.height

}


funcmain(){
	varrRectangle
	r=Rectangle{width:20,height:10}
	r=Rectangle{20,10}
	fmt.Println("theRectanglewidth:",r.width)
	fmt.Println("theareaofRectangle:",r.area())//直接调用area函数
}
//执行结果:
theRectanglewidth:20
theareaofRectangle:200//计算结果为200

3、结构体方法接收类型为指针,则能改变原结构体的属性值

我们先将类型设置为值类型看看

packagemain

import"fmt"

typeRectanglestruct{
	widthfloat64
	heightfloat64
}

func(r*Rectangle)area()float64{
	returnr.width*r.height

}
func(rRectangle)changeWidth(){//把接收体的类型设置为值类型
	r.width=30
}

funcmain(){
	varrRectangle
	r=Rectangle{width:20,r.area())
	r.changeWidth()//改变了width
	fmt.Println("theRectanglewidth:",r.width)//打印结果
}
//执行结果:
theRectanglewidth:20
theareaofRectangle:200
theRectanglewidth:20//结果显示并没有改变

我们将接收体设置为指针

packagemain

import"fmt"

typeRectanglestruct{
	widthfloat64
	heightfloat64
}

func(r*Rectangle)area()float64{
	returnr.width*r.height

}
func(r*Rectangle)changeWidth(){//指针类型
	r.width=30
}

funcmain(){
	varrRectangle
	r=Rectangle{width:20,r.area())
	r.changeWidth()
	fmt.Println("theRectanglewidth:",r.width)
}
//执行结果:
theRectanglewidth:20
theareaofRectangle:200
theRectanglewidth:30//结果显示已经改变了width的值

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读