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

有没有一种方法可以在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
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • duai4512 2017-11-25 13:27

    The Go Programming Language Specification

    Built-in functions

    Built-in functions are predeclared. They are called like any other function but some of them accept a type instead of an expression as the first argument.

    The built-in functions do not have standard Go types, so they can only appear in call expressions; they cannot be used as function values.


    The Go programming language does not allow function overloading except for Go built-in functions. There is no way for you to overload your functions.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题