【问题标题】:How can I improve this program in a few lines of code? [closed]如何用几行代码改进这个程序? [关闭]
【发布时间】:2021-02-18 11:35:17
【问题描述】:

我正在尝试创建一个不和谐的机器人来检查消息是否包含存储在数组中的字符串。 我尝试使用 for 循环但它不起作用,因为它永远持续,我想减少代码行数,有什么办法吗?

switch {
    case strings.Contains(mContent, characterss[0]):
        currentCharacter = characterss[0]
        currentDescription = descriptions[0]
        currentImage = images[0]
        isCorrect = true
    case strings.Contains(mContent, characterss[1]):
        currentCharacter = characterss[1]
        currentDescription = descriptions[1]
        currentImage = images[1]
        isCorrect = true
    case strings.Contains(mContent, characterss[2]):
        currentCharacter = characterss[2]
        currentDescription = descriptions[2]
        currentImage = images[2]
        isCorrect = true
    case strings.Contains(mContent, characterss[3]):
        currentCharacter = characterss[3]
        currentDescription = descriptions[3]
        currentImage = images[3]
        isCorrect = true
    case strings.Contains(mContent, characterss[4]):
        currentCharacter = characterss[4]
        currentDescription = descriptions[4]
        currentImage = images[4]
        isCorrect = true
    case strings.Contains(mContent, characterss[5]):
        currentCharacter = characterss[5]
        currentDescription = descriptions[5]
        currentImage = images[5]
        isCorrect = true
    case strings.Contains(mContent, characterss[6]):
        currentCharacter = characterss[6]
        currentDescription = descriptions[6]
        currentImage = images[6]
        isCorrect = true
    }

【问题讨论】:

  • 让我问你这个。在这里看到模式吗?
  • 是的,我的没有用,因为我使用了 len(characterss) 而不是元素总数,idk 实际上为什么 len 没有用

标签: arrays for-loop go switch-statement discord


【解决方案1】:

只需使用循环:

for i := 0; i <= 6; i ++ {
    if strings.Contains(mContent, characeterss[i]) {
        currentCharacter = characterss[i]
        currentDescription = descriptions[i]
        currentImage = images[i]
        isCorrect = true
        break
    }
}

【讨论】:

  • 非常感谢您的帮助,实际上我认为我的不起作用,因为它有 len(characterss) 而不是 6。我不知道为什么 len 不起作用
猜你喜欢
  • 2017-06-12
  • 2020-10-22
  • 1970-01-01
  • 2017-12-01
  • 2010-09-12
  • 2012-05-20
  • 2020-05-26
  • 1970-01-01
  • 2023-04-10
相关资源
最近更新 更多