网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

golangstruct-创新互联

struct

波密ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为成都创新互联公司的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:18980820575(备注:SSL证书合作)期待与您的合作!

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的值

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


本文题目:golangstruct-创新互联
当前路径:http://bjjierui.cn/article/ccjshe.html

其他资讯