原諒我所有的評論,我正在學習,這讓我保持直截了當。在底部附近為我的條件陳述句尋找更好的解決方案,并提供其余的背景關系。嘗試了建議的回圈注釋,但仍然沒有得到這里寫的正確結果
// define the main package file
package main
//importing formatting features for the user I/O and string manipulation packages
//Parenthesis not needed if only importing 1 package
import (
"fmt"
"strings"
)
// defining the main function of the standalone app
func main() {
//initializing a string array
options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
//creating a slice in the array to designate favorites
favFruits := options[0:3]
fmt.Println(options)
//initializing variable for user input
var fruit string
fmt.Print("Favorite Fruit Not Listed: ")
fmt.Scan(&fruit)
//convert response to lowercase
fruitConv := strings.ToLower(fruit)
//conditional statement example
for _, pick := range options {
if pick == fruitConv {
fmt.Println("You were supposed to pick something else")
break
} else {
fmt.Println("Response Accepted!")
break
}
break
}
//adding user inputed favorite fruit to the sliced array
favFruits = append(favFruits, fruitConv)
fmt.Print(favFruits)
}
uj5u.com熱心網友回復:
我明白你的意思了。如果你去官方Go packages部分,你會slices在那里得到包裹。參考:切片
contains包內有一個命名的函式slices,您可以使用該函式。為簡單起見,我創建了一個與您的場景匹配的示例。
func main() {
//initializing a string array
options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
// assuming fruit as user input
fruit := "lemon"
//conditional statement example
if fruit == "coconut" || fruit == "coconuts" {
fmt.Println("Coconuts are nasty (except on your hair/skin)")
//**there has to be a way to simplify this code if the array grows server-side or something**
} else if slices.Contains(options, fruit) {
fmt.Println("You were supposed to pick something different...")
}
}
這是作業鏈接:- https://goplay.tools/snippet/bzSm_biR4Vr
注意:由于在您的場景中有很多這樣的包含檢查,我建議使用map而不是切片。在內部,如果您深入研究 slice 的 conatins 功能,您將了解。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/516947.html
上一篇:Git合并,但添加了所有沖突的行
下一篇:從GRPC獲取請求詳細資訊
