Go语言入门(14)-struct

发布于:2025-08-30 ⋅ 阅读:(10) ⋅ 点赞:(0)

struct-结构类型:将分散的零件组成一个完整的结构体,并且可将不同类型的东西组合在一起。

package main

import (
	"fmt"
)

func distance(lat1, long1, lat2, long2 float64) float64 {
	return 0.0
}

func main() {
	var curiosity struct { //此处的curiosity为struct类型的变量,而不是类型,无法复用
		lat  float64
		long float64
	}

	curiosity.lat = -4.5895
	curiosity.long = 137.4417

	fmt.Println(curiosity.lat, curiosity.long)
	fmt.Println(curiosity)
}

通过类型复用结构体:

package main

import (
	"fmt"
)

func distance(lat1, long1, lat2, long2 float64) float64 {
	return 0.0
}

func main() {
	var spirit location
	spirit.lat = 14.5684
	spirit.long = 175.472636

	var opportunity location
	opportunity.lat = -1.9462
	opportunity.long = 354.3734

	fmt.Println(spirit, opportunity)
}

通过复合字面值初始化Struct:

package main

import (
	"fmt"
)

//通过复合字面值初始化Struct:
func distance(loc1, loc2 location) dis {
	return dis{0.0, 0.0}
}

type dis struct {
	lat  float64
	long float64
}

func main() {
//内容
}

通过成对的字段和值进行初始化:

package main

import "fmt"

func main() {
    type location1 struct {
		lat1, long1 float64
	}

	opportunity1 := location1{lat1: -1.9462, long1: 354.6849}
	fmt.Println(opportunity1)

	insight := location1{lat1: 4.5, long1: 135.98}
	fmt.Println(insight)
}

按字段定义的顺序进行初始化:

package main

import "fmt"

func main() {
    type location1 struct {
		lat1, long1 float64
	}

	opportunity1 := location1{lat1: -1.9462, long1: 354.6849}
	fmt.Println(opportunity1)

	insight := location1{lat1: 4.5, long1: 135.98}
	fmt.Println(insight)

    spirit := location{-14.5684,175.4723}
    fmt.Println(spirit)
}

打印struct:

Struct的复制:

由结构体组成的slice:

package main

import "fmt"

func main() {
    type locas struct {
		name  string
		lat2  float64
		long2 float64
	}

	lats := []float64{-4.598, -14, 626, -1.94923}
	longs := []float64{137.4419, 175.7272, 354.2323}

	locations := []locas{
		{name: "Bradbury Landing", lat2: -9.998, long2: 8.999},
		{name: "Columbia Memorial Station", lat2: -2352.22, long2: -18.23},
		{name: "Challenger Memorial Station", lat2: -1.9582, long2: 354.256},
	}
	//fmt.Println("=======================")
	fmt.Println(lats, longs, locations)
}

补充:将struct编码为JSON(JavaScript Object Notation,JavaScript对象表示法)

常用于Web API

json包的Marshal函数可以将struct中的数据转化为JSON格式:

package main

import (
	"encoding/json"
	"fmt"
	"os"
)

func main() {
	type location struct {
		//Lat, Long float64 //PS:结构体里,类型名的首字母必须大写,转换成JSON后才有有效输出。小写无法导出

		//法2标签法:使得json包在进行编码的时候能够按照标签里的样式修改字段名
		Lat  float64 `json:"latitude"`
		Long float64 `json:"longtitude"`
	}

	curiosity := location{-4.5895, 137.4417}

	bytes, err := json.Marshal(curiosity)
	exitOnError(err)

	fmt.Println(string(bytes))
}

func exitOnError(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

需要注意的是,结构体里,类型名的首字母必须大写,转换成JSON后才有有效输出。小写无法导出