package main
import (
"fmt"
)
var curosity struct {
lat float64
lon float64
}
func main() {
curosity.lat = 64
curosity.lon = 128
fmt.Println(curosity.lat,curosity.lon)
fmt.Println(curosity)
}
package main
import (
"fmt"
)
//If you need multiple structures with the same fields, you can define a type
type test struct{
lat float64
}
// 实例
var t1,t2 test
func main() {
t1.lat = 19
fmt.Println(t1)
t2.lat = 20
fmt.Println(t2)
// 使用 +v 来debug
t := test{1}
fmt.Printf("%+v\n",t)
fmt.Printf("%+v\n",t1)
}
package main
import (
"fmt"
"encoding/json"
)
func main() {
// 将go语言转为json
type localtion struct{
Long,Lat float64 // Notice that the JSON keys match the field names of the structure. For this to location work, the package requires fields to be exported json
}
l := localtion{-4.023,2.5000}
b,_:= json.Marshal(l)
fmt.Println(string(b)) // {"Long":-4.023,"Lat":2.5}
//==========================================================
// 如果你希望在json里面自定义 key 值,因为有时候json里面的key 值都是小写的
type location2 struct{
Long float64 `json:"longitude"` // 不能有空格
Lat float64 `json:"latitude"`
}
l2 := location2{1,2.0}
b,_ = json.Marshal(l2)
fmt.Println(string(b)) // {"longitude":1,"latitude":2}
}
package main
import (
"fmt"
"strconv"
)
func test() string {
return "Hello"
}
type person struct {
name string
age int
}
func (p person) info() string{
return "My name is " + p.name + "and my age is " + strconv.Itoa(p.age) // 类型转换
}
func main() {
// go 中没有 对象 这一说法,但是你还是可以定义方法
// 注意: struct 可以定义在 main 函数里面,但是方法无法定义在main 函数里面,会出现错误
fmt.Println(test())
p1 := person{"John",20}
fmt.Println(p1)
fmt.Println(p1.info())
}
package main
import (
"fmt"
"strconv"
)
func test() string {
return "Hello"
}
type person struct {
name string
age int
}
func (p person) info() string{
return "My name is " + p.name + " and my age is " + strconv.Itoa(p.age) // 类型转换
}
// 构造函数
func newPerson(name string,age int) person {
return person{name,age}
}
func main() {
p := newPerson("John",20)
fmt.Println(p.info())
}
package main
import (
"fmt"
)
// 试想,如果一个struct 有很多的属性,都写在一个 struct 里面,代码的可读性就会变得很差
// 最佳的做法,对一个大类的 struct 的定义,应该是通过分部分来进行定义,然后内嵌进去,组成一个大的类
type animal struct {
name string
age int
cat // cat struct
bird // bird struct
}
type cat struct {
foot bool
}
type bird struct {
fly bool
}
func (c cat) eat() {
fmt.Println("I am Cat and I eat")
}
func (b bird) flys() {
if b.fly{
fmt.Println("I am Bird and i can flys")
}else{
fmt.Println("I am not Bird and I can't flys ")
}
}
func main() {
// 只要在 struct里面内嵌另外的 struct 就可以转发他们定义的方法
a:= animal{"animal",12,cat{true},bird{false}}
// 但是如果内嵌的多个 struct 里面,有方法重名的话,就会出现错误。
a.eat()
a.flys()
// 重名的情况下,需要具体指出是哪个内嵌的struct的方法
a.cat.flys()
}