doushuzd3033 2018-07-07 15:28
浏览 64
已采纳

从嵌套块返回,范围问题

Basic concept

I'm learning Go and I can't understand how to return data from an inner block of a function.

package main

import (
    "fmt"
)

func main() {
    fmt.Println("Hello, playground")
    if isTrue("asasa") {
        fmt.Println("isTrue is true")
    }
}

func isTrue(s string) bool {
    if s == "asasa" {
        fmt.Println("it matches")
        return true
    }
}

https://play.golang.org/p/x6l29CNdg-o

How should I return a condition met inside a nested (even multiple time nested) block?

Real case scenario

func isUnique(h, c, L float64) bool {

    for i, color := range usuedColors {
        if color[0] == h && color[1] == c && color[2] == L {
            fmt.Println("This color already exist!")
            return false
        } else {
            return true
        }
    }
}

I receive a triple of values h, c, L and I want to check if it is unique against a 2D slice where I've previously stored other triples. I cycle through all the triple and if a match exist I want isUnique to return as false, else true.

  • 写回答

3条回答 默认 最新

  • dsf22567 2018-07-07 15:35
    关注

    Check for value returned from the function, assign it to variable and use it in main when checking for the condition as below: package main

    import (
        "fmt"
    )
    
    func main() {
        fmt.Println("Hello, playground")
        if ok := isTrue("asasa"); ok {
            fmt.Println("isTrue is true")
        }
    }
    
    func isTrue(s string) bool {
        boolean := false
        for i := 0; i < 5; i++ {
            if s == "asasa" {
                fmt.Println("it matches")
                boolean = true
            }
        }
        return boolean
    }
    

    In Golang Effective Go for If control statement it is described:

    Since if and switch accept an initialization statement, it's common to see one used to set up a local variable.

    if err := file.Chmod(0664); err != nil {
        log.Print(err)
        return err
    }
    

    In the Go libraries, you'll find that when an if statement doesn't flow into the next statement—that is, the body ends in break, continue, goto, or return—the unnecessary else is omitted.

    f, err := os.Open(name)
    if err != nil {
        return err
    }
    codeUsing(f)
    

    It is also used in maps to check if value exists or not on basis of keys. Check this link for Effective Go on maps to know more about comma ok syntax.

    Working code updated on Go playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP