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条)

报告相同问题?

悬赏问题

  • ¥20 数学建模数学建模需要
  • ¥15 c语言数据结构实验单链表的删除
  • ¥15 关于#lua#的问题,请各位专家解答!
  • ¥15 什么设备可以研究OFDM的60GHz毫米波信道模型
  • ¥15 不知道是该怎么引用多个函数片段
  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决