温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

golang struct

发布时间:2020-07-05 02:21:58 来源:网络 阅读:361 作者:欺世 栏目:开发技术

struct


1、定义一个struct

package main

import "fmt"

type Rectangle struct {        
	width float64
	height float64
}

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

2、给结构体定义方法

package main

import "fmt"

type Rectangle struct {
	width float64
	height float64
}

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

}


func main(){
	var r Rectangle
	r = Rectangle{width:20,height:10}
	r = Rectangle{20,10}
	fmt.Println("the Rectangle width:",r.width)
	fmt.Println("the area of Rectangle: ",r.area())  //直接调用area函数
}
//执行结果:
the Rectangle width: 20
the area of Rectangle:  200   //计算结果为200

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

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

package main

import "fmt"

type Rectangle struct {
	width float64
	height float64
}

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

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

func main(){
	var r Rectangle
	r = Rectangle{width:20,height:10}
	r = Rectangle{20,10}
	fmt.Println("the Rectangle width:",r.width)
	fmt.Println("the area of Rectangle: ",r.area())
	r.changeWidth()                 //改变了width
	fmt.Println("the Rectangle width:",r.width) //打印结果
}
//执行结果:
the Rectangle width: 20
the area of Rectangle:  200
the Rectangle width: 20               //结果显示并没有改变

我们将接收体设置为指针

package main

import "fmt"

type Rectangle struct {
	width float64
	height float64
}

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

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

func main(){
	var r Rectangle
	r = Rectangle{width:20,height:10}
	r = Rectangle{20,10}
	fmt.Println("the Rectangle width:",r.width)
	fmt.Println("the area of Rectangle: ",r.area())
	r.changeWidth()
	fmt.Println("the Rectangle width:",r.width)
}
//执行结果:
the Rectangle width: 20
the area of Rectangle:  200
the Rectangle width: 30                 //结果显示已经改变了width的值


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI