登录
首页 >  Golang >  Go问答

如何用几行代码改进这个程序?

来源:stackoverflow

时间:2024-04-21 23:36:21 457浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《如何用几行代码改进这个程序?》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我正在尝试创建一个不和谐的机器人来检查消息是否包含存储在数组中的字符串。 我尝试使用 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
    }

解决方案


只需使用循环:

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

好了,本文到此结束,带大家了解了《如何用几行代码改进这个程序?》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>