九、结构体
Go语言的结构体和C语言是类似的。定义结构体如下:
type books struct {
sName string
sAuthor string
nID int64
fPrice float64
sOwner string
}
使用结构体有两种办法:
var myBook books
myBook.sName ="Go语言实战"
myBook.sAuther = "Tank"
myBook.nID =139581
myBook.fPrice = 58.88
myBook.sOwner ="Tank"
theBook :=books{"Go语言实战", "Tank", 139581, 58.88, "Dennis"}
yourBook := books{sName:"Go语言实战",sAuther: "Tank", nID: 139581, fPrice: 58.88, sOwner: "Dennis"}
后两个是直接用:=赋值来声明结构变量。
示例程序如下:
package main
import "fmt"
type books struct {
sName string
sAuthor string
nID int64
fPrice float64
sOwner string
}
func main(){
var myBook books
myBook.sName ="Go语言实战"
myBook.sAuthor = "Tank"
myBook.nID =139581
myBook.fPrice = 58.88
myBook.sOwner ="Tank"
theBook :=books{"Go语言实战", "Tank", 139581, 58.88, "Dennis"}
yourBook := books{sName:"Go语言实战",sAuthor: "Tank", nID: 139581, fPrice: 58.88, sOwner: "Marry"}
fmt.Println(myBook)
fmt.Println(theBook)
fmt.Println(yourBook)
}
运行结果如下:
D:\Documents\GoTrial>go run struct.go
{Go语言实战 Tank 139581 58.88 Tank}
{Go语言实战 Tank 139581 58.88 Dennis}
{Go语言实战 Tank 139581 58.88 Marry}
十、函数
go语言函数声明如下:
func plusFour(a int64,b int64,c int64,d int64) int64{
ret :=a + b + c + d
return ret
}
go语言函数可以有多个返回值,例如:
func dealInt(a int64, b int64) (int64,int64){
ret1 :=a/b
ret2 :=a%b
return ret1,ret2
}
程序如下:
package main
import "fmt"
func main(){
a := plusFour(54,35,66,82)
fmt.Println(a)
fmt.Println(dealInt(88,3))
}
func plusFour(a int64,b int64,c int64,d int64) int64{
ret :=a + b + c + d
return ret
}
func dealInt(a int64, b int64) (int64,int64){
ret1 :=a/b
ret2 :=a%b
return ret1,ret2
}
运行结果如下
D:\Documents\GoTrial>go run functions.go
237
29 1
十一、结构体带方法
结构体可以带上自己的函数,如下面的程序所示, nArea()就是结构体rect的函数
package main
import "fmt"
type rect struct {
nWidth, nHeight int64
}
func (r rect) nArea() int64 {
return r.nWidth * r.nHeight
}
func main(){
myR :=rect{25,34}
fmt.Println(myR)
fmt.Println(myR.nArea())
}
程序运行结果如下:
D:\Documents\GoTrial>go run structfunc.go
{25 34}
850
有疑问加站长微信联系(非本文作者)