drz49609 2017-11-25 13:15
浏览 125
已采纳

有没有一种方法可以在Go中重载功能?

I have read that there is no way to overload a function in Go. I mean by overloading, a way to have two functions with the same name but with different arguments.

I have seen something strange in the built-in functions of Go:

Let's suppose ch1 is a channel variable:

ch1 := make(chan string)

It is possible to read somthing from a channel like this:

result := <-ch1

But it is also possible to get a status like this:

result, status := <-ch1

So, is there is a way to overloaded a function like a built-in function?

  • 写回答

2条回答 默认 最新

  • dopgv00024 2017-11-25 13:31
    关注

    No.

    For obvious reasons this is called the comma ok idiom (not a function overload ):

    result, status := <-ch1
    

    1- Try this for Channels:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        ch1 := make(chan string, 1)
        ch1 <- `Hi`
        result, status := <-ch1
        fmt.Println(result, status) // Hi true
    
        ch1 <- `Hi`
        close(ch1)
        result, status = <-ch1
        fmt.Println(result, status) // Hi true
    
        result, status = <-ch1
        fmt.Println(result, status) //    false
    }
    

    output:

    Hi true
    Hi true
     false
    

    2- Try this for Maps:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        m := map[string]int{"One": 1, "Two": 2}
    
        result, status := m["One"]
        fmt.Println(result, status) // 1 true
    
        result, status = m["Two"]
        fmt.Println(result, status) // 2 true
    
        result, status = m["Zero"]
        fmt.Println(result, status) //  0  false
    }
    

    output:

    1 true
    2 true
    0 false
    

    3- Try this for interface conversions and type assertions:

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        var s interface{} = `One`
    
        result, status := s.(string)
        fmt.Println(result, status) // One true
    
        i, status := s.(int)
        fmt.Println(i, status) // 0 false
    }
    

    output:

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

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算