Golang中如何缩短代码 - switch语句的优化技巧

Golang中如何缩短代码 - switch语句的优化技巧 大家好,

我正在为一个棋盘游戏编写一个简单的代码。它应该从16个可能的选项中抽取两个、三个或四个国家(取决于有多少玩家参与)。不能有重复。

以下是关键部分:

					rand.Seed(time.Now().UnixNano())
		
					var a = rand.Intn(17-1)+1		

					switch a {				
						case 1: 
						fmt.Println("uranopolis")
						case 2: 
						fmt.Println("smart")
						case 3: 
						fmt.Println("sand runners")
						case 4: 
						fmt.Println("policja")
						case 5: 
						fmt.Println("dancer")
						case 6: 
						fmt.Println("nowy jork")
						case 7: 
						fmt.Println("missisipi")
						case 8: 
						fmt.Println("vegas")	
						case 9: 
						fmt.Println("neodżungla")
						case 10: 
						fmt.Println("troglodyci")
						case 11: 
						fmt.Println("szczury")
						case 12: 
						fmt.Println("iron gang")
						case 13: 
						fmt.Println("borgo")
						case 14: 
						fmt.Println("hegemonia")
						case 15: 
						fmt.Println("moloch")
						case 16: 
						fmt.Println("posterunek")	
					}

我曾经将这个代码块重复了四次(因为要抽取四次)。我想缩短它;我希望上面的代码部分只出现一次。 是否有可能将这部分:

  			switch a {				

改成类似这样的形式(我知道下面的语法是错误的):

  			switch a, b, c, d {				

换句话说:我希望代码能一次性抽取四个玩家:玩家a、b、c、d。仅使用我粘贴在这里的这个“switch”代码块。 代码还有一个输入框(有多少玩家在玩?[2-4])。即使我们选择2个玩家,代码也可以抽取4个玩家——这没关系,因为代码最终会根据我们声明的玩家数量打印出相应数量的输出。

有没有一种神奇的语法可以帮助我?我认为在代码中重复四次几乎相同的文本块很混乱。

干杯!


更多关于Golang中如何缩短代码 - switch语句的优化技巧的实战教程也可以访问 https://www.itying.com/category-94-b0.html

7 回复

你想要的与 switch 语句无关。

你真正需要的是创建一个单一的函数,然后调用它四次。

更多关于Golang中如何缩短代码 - switch语句的优化技巧的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


感谢您的回复。我认为 @NobbZ 说得对。我应该创建一个函数,从16个可能的国家中抽取一个,并将这部分代码放入“通用”函数中,在那里根据输入数据,将按需调用“抽取”函数多次。 我是一个初学者,所以我很期待测试你们的所有建议。谢谢!

这是你想表达的意思吗?对于具有公共代码的 case 使用 fallthrough:

case 1: fallthrough
case 2: fallthrough
case 3:
         commonOperationForCases1Through3()
case 4: // 等等。

抱歉,我粗略地浏览了问题,回答了一个不同的问题。

我不确定其他人的回答是否解决了你的问题,但在我看来,你似乎想要一个 for 循环?类似这样:

numberOfNations := askUserForNumberOfNations()

for i := 0; i < numberOfNations; i++ {
    nationCode := askUserForNationCode()
    a := nationCode
    switch a {
        case 1:
        // ...
    }
}

也许可以这样做:

package main

import "fmt"

var cities = map[int]string{
	0: "uranopolis", 1: "smart", 2: "sand runners", 3: "policja"}

func main() {
	fmt.Println(GetNation(0))
	fmt.Println(GetNation(1))
	fmt.Println(GetNation(2))
}

func GetNation(selectedNr int) string {
	if value, ok := cities[selectedNr]; ok {
		delete(cities, selectedNr)
		return value
	}
	return ""
}

类似这样吗? https://play.golang.com/p/ynx7Uxq4ga2

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())  // change the seed manually in "The Go Playground"
	players := getFirstX(rand.Intn(4) + 1)
	for i := range players {
		fmt.Println(players[i])
	}
}

func getFirstX(X int) []string {
	data := []string{"uranopolis", "smart", "sand runners", "policja", "dancer"}
	rand.Shuffle(len(data), func(i, j int) { data[i], data[j] = data[j], data[i] })
	return data[:X]
}

可以使用切片存储国家名称,通过随机索引来避免重复抽取,这样switch语句就不再需要。以下是优化后的代码示例:

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	
	countries := []string{
		"uranopolis",
		"smart",
		"sand runners",
		"policja",
		"dancer",
		"nowy jork",
		"missisipi",
		"vegas",
		"neodżungla",
		"troglodyci",
		"szczury",
		"iron gang",
		"borgo",
		"hegemonia",
		"moloch",
		"posterunek",
	}

	// 打乱国家顺序
	rand.Shuffle(len(countries), func(i, j int) {
		countries[i], countries[j] = countries[j], countries[i]
	})

	// 根据玩家数量抽取(假设playerCount已定义)
	playerCount := 4 // 示例值,实际应从输入获取
	for i := 0; i < playerCount; i++ {
		fmt.Println(countries[i])
	}
}

或者使用map来确保不重复的随机选择:

func selectCountries(playerCount int) []string {
	countries := []string{
		"uranopolis", "smart", "sand runners", "policja",
		"dancer", "nowy jork", "missisipi", "vegas",
		"neodżungla", "troglodyci", "szczury", "iron gang",
		"borgo", "hegemonia", "moloch", "posterunek",
	}
	
	selected := make([]string, 0, playerCount)
	used := make(map[int]bool)
	
	for len(selected) < playerCount {
		idx := rand.Intn(len(countries))
		if !used[idx] {
			used[idx] = true
			selected = append(selected, countries[idx])
		}
	}
	
	return selected
}

这样只需调用一次函数即可获得所需数量的不重复国家。

回到顶部