使用Go语言,在将用户输入附加到切片时避免重复的现有数组数据。

huangapple go评论121阅读模式
英文:

Using Go to avoid duplicates from existing array data when appending slices with user input

问题

请原谅我所有的评论,我正在学习,这使我保持专注。我正在寻找一个更好的解决方案来处理我在底部附近的条件语句,并提供其余的内容以供参考。我尝试了建议的循环注释,但仍然没有得到正确的结果,如下所示:

// 定义主包文件
package main

// 导入用户I/O和字符串操作包的格式化功能
// 如果只导入一个包,括号是不需要的
import (
"fmt"
"strings"
)

// 定义独立应用程序的主函数
func main() {

  1. // 初始化一个字符串数组
  2. options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
  3. // 在数组中创建一个切片来指定喜爱的水果
  4. favFruits := options[0:3]
  5. fmt.Println(options)
  6. // 初始化用户输入的变量
  7. var fruit string
  8. fmt.Print("Favorite Fruit Not Listed: ")
  9. fmt.Scan(&fruit)
  10. // 将响应转换为小写
  11. fruitConv := strings.ToLower(fruit)
  12. // 条件语句示例
  13. for _, pick := range options {
  14. if pick == fruitConv {
  15. fmt.Println("You were supposed to pick something else")
  16. break
  17. } else {
  18. fmt.Println("Response Accepted!")
  19. break
  20. }
  21. break
  22. }
  23. // 将用户输入的喜爱水果添加到切片数组中
  24. favFruits = append(favFruits, fruitConv)
  25. fmt.Print(favFruits)

}

英文:

Forgive all my comments, I'm learning and that keeps me straight. Looking for a better solution to my conditional statement near the bottom and provided the rest for context. Tried out the loop comment suggested, but still not getting the right result as written here

  1. // define the main package file
  2. package main
  3. //importing formatting features for the user I/O and string manipulation packages
  4. //Parenthesis not needed if only importing 1 package
  5. import (
  6. "fmt"
  7. "strings"
  8. )
  9. // defining the main function of the standalone app
  10. func main() {
  11. //initializing a string array
  12. options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
  13. //creating a slice in the array to designate favorites
  14. favFruits := options[0:3]
  15. fmt.Println(options)
  16. //initializing variable for user input
  17. var fruit string
  18. fmt.Print("Favorite Fruit Not Listed: ")
  19. fmt.Scan(&fruit)
  20. //convert response to lowercase
  21. fruitConv := strings.ToLower(fruit)
  22. //conditional statement example
  23. for _, pick := range options {
  24. if pick == fruitConv {
  25. fmt.Println("You were supposed to pick something else")
  26. break
  27. } else {
  28. fmt.Println("Response Accepted!")
  29. break
  30. }
  31. break
  32. }
  33. //adding user inputed favorite fruit to the sliced array
  34. favFruits = append(favFruits, fruitConv)
  35. fmt.Print(favFruits)
  36. }

答案1

得分: 0

我明白了。如果你去官方的Go packages部分,你会找到slices包。参考链接:slices

slices包中有一个名为contains的函数,你可以使用这个函数。为了简单起见,我创建了一个与你的场景匹配的示例。

  1. func main() {
  2. //初始化一个字符串数组
  3. options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
  4. //假设水果是用户输入
  5. fruit := "lemon"
  6. //条件语句示例
  7. if fruit == "coconut" || fruit == "coconuts" {
  8. fmt.Println("Coconuts are nasty (except on your hair/skin)")
  9. //**如果数组在服务器端增长,应该有简化这段代码的方法**
  10. } else if slices.Contains(options, fruit) {
  11. fmt.Println("You were supposed to pick something different...")
  12. }
  13. }

这是工作链接:https://goplay.tools/snippet/bzSm_biR4Vr

**注意:**由于在你的场景中有很多这样的包含检查,我建议使用map而不是切片。如果你深入研究切片的包含函数,你会了解到其中的原理。

英文:

I got your point. If you go to official Go packages section you will get slices package over there. Ref: slices

There is one function named contains inside the slices package, you can make use of that function. For your simplicity, I have created one example matching with your scenario.

  1. func main() {
  2. //initializing a string array
  3. options := []string{"lemon", "orange", "strawberry", "banana", "grape"}
  4. // assuming fruit as user input
  5. fruit := "lemon"
  6. //conditional statement example
  7. if fruit == "coconut" || fruit == "coconuts" {
  8. fmt.Println("Coconuts are nasty (except on your hair/skin)")
  9. //**there has to be a way to simplify this code if the array grows server-side or something**
  10. } else if slices.Contains(options, fruit) {
  11. fmt.Println("You were supposed to pick something different...")
  12. }
  13. }

Here is the working link :- https://goplay.tools/snippet/bzSm_biR4Vr

Note: Since in your scenario there is lot of such contain checks, I would recommend to use map instead of slice. Internally if you deep dive in conatins function of slice you will get to know.

huangapple
  • 本文由 发表于 2022年10月18日 14:43:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/74106710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定