golang 制作地图类型Go in Go

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 制作地图类型Go in Go相关的知识,希望对你有一定的参考价值。

package main

import "fmt"

func main() {
	ages := map[string]int{
		"Peterson": 52,
		"Sally":    22,
		"Javovia":  15,
		"Ben":      42,
	}

	jobAssociation := make(map[string]string)
	jobAssociation["Peterson"] = "Engineer"
	jobAssociation["Sally"] = "CEO"
	jobAssociation["Jovovia"] = "Gamer"
	jobAssociation["Ben"] = "Programmer"

	printAges(ages)
	printJobAssociations(jobAssociation)

	fmt.Println(ages)
	fmt.Println(jobAssociation)
	fmt.Println(jobAssociation["Jovovia"])
	fmt.Println(jobAssociation["Frank"]) // Blank! :o
	fmt.Println(ages["Sally"])

	delete(ages, "Sally")

	fmt.Println(ages)
	fmt.Println(ages["Sally"])

	delete(jobAssociation, "Jovovia")

	fmt.Println(jobAssociation)
	fmt.Println(jobAssociation["Jovovia"]) // Blank.

	ages2 := map[string]int{
		"Frank":     52,
		"Johnson":   22,
		"Smith":     15,
		"Jezebelle": 42,
	}

	ages3 := map[string]int{
		"Frank":     52,
		"Johnson":   22,
		"Smith":     15,
		"Jezebelle": 42,
	}

	if equal(ages, ages2) {
		fmt.Println("Naw, not really equal.")
	} else {
		fmt.Println("This is correct, not equal.")
	}

	if equal(ages2, ages3) {
		fmt.Println("True, these are effectively the same map values and keys.")
	}
}

func printJobAssociations(associations map[string]string) {
	for name, job := range associations {
		fmt.Printf("%s\t%s\n", name, job)
	}
}

func printAges(ages map[string]int) {
	for name, age := range ages {
		fmt.Printf("%s\t%d\n", name, age)
	}
}

func equal(x, y map[string]int) bool {
	if len(x) != len(y) {
		return false
	}
	for k, xv := range x {
		if yv, ok := y[k]; !ok || yv != xv {
			return false
		}
	}
	return true
}

golang 分开并加入strs in go

package main
//splits and joins strs
import "fmt"
import s "strings"

func main() {
    fmt.Print(joinstr(splitstr("hello how are you today", " ")))
}
//splits strings be a delimeter
func splitstr(input, delim string) []string{
    return s.Split(input, delim)
}
//joins a string of arrays together
func joinstr(input []string) string{
    return s.Join(input, "")
}

以上是关于golang 制作地图类型Go in Go的主要内容,如果未能解决你的问题,请参考以下文章

golang Go中的地图声明

golang 密钥存在检查Go地图

golang 将func放入go中的地图中

golang 允许你在go中嵌入一个结构中的地图

如何在 Go (Golang) 中检索表单数据作为地图(如 PHP 和 Ruby)

golang 分开并加入strs in go