R
R
Roman Rakzin2015-07-23 16:33:58
go
Roman Rakzin, 2015-07-23 16:33:58

How to create an overloaded function in golang?

How to make one function and the same one could take different types of parameters?
for example, if it receives an incoming int parameter, then one thing is done, if a string is something else.
For example

func myfunc(??? ){
    //какое-нибудь одинаковое действие для обоих вариантов
    log.Println("Мне передали число,идём по пути 1")//или...
    log.Println("Мне передали строку,идём по пути 2")
    }

Or it is necessary to write 2 different functions?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Rakzin, 2015-07-23
@TwoRS

Solved play.golang.org/p/EUmI1N2OYp

func f(v interface{}) {
    switch v.(type) {
    case int:
        fmt.Println("int", v)
    case string:
        fmt.Println("string", v)
    default:
        panic(fmt.Sprintf("f: unsupported type %T", v))
    }
}

I
index0h, 2015-07-24
@index0h

In vain you are so)) Use static typing, and do not replace it with dynamic where it is not necessary))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question