golang struct

golang struct,第1张

概述struct 1、定义一个struct package mainimport "fmt"type Rectangle struct {         width float64 height float64}func main(){ var r Rectangle       //声明一个结构体  r,width height的值为“零”值。在这里为0.0,0.0 r = 

struct


1、定义一个struct

packagemainimport"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、给结构体定义方法

packagemainimport"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:20theareaofRectangle:200//计算结果为200

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

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

packagemainimport"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:20theareaofRectangle:200theRectanglewIDth:20//结果显示并没有改变

我们将接收体设置为指针

packagemainimport"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:20theareaofRectangle:200theRectanglewIDth:30//结果显示已经改变了wIDth的值
总结

以上是内存溢出为你收集整理的golang struct全部内容,希望文章能够帮你解决golang struct所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1279458.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-09
下一篇 2022-06-09

发表评论

登录后才能评论

评论列表(0条)

保存