If  I want to  cast interface{} to float64
interface{} could be int8 int16 int32 int64 float32.....
What is the proper way.

consider    a generic function  for min
func Min(a T, b T) T {
}
What is the best way to implement it in go

2017-01-12 10:52 GMT+08:00 Dan Kortschak <dan.kortsc...@adelaide.edu.au>:

> What are you trying to do?
>
> The behaviour of LimRange as you have it here is to return the float64
> value of x if it is a float64, zero if it is another numerical type in
> the case list and NaN if it is none of those.
>
> I would suggest you read https://golang.org/ref/spec#Switch_statements
> particularly Type Switches where it says
>
> ```
> In clauses with a case listing exactly one type, the variable has that
> type; *otherwise, the variable has the type of the expression in the
> TypeSwitchGuard*.
> ```
>
> This means that in the case as you have it below with
> `case int,int8,int16,int32,float32,float64:` the type of v must be the
> type of x, which is interface{}. You cannot convert interface{} to
> float64.
>
> On Wed, 2017-01-11 at 18:35 -0800, hui zhang wrote:
> > This is a compile error,   so I don't think this matter
> > I modify the code ,   add float ,  it is the same.
> >
> > func LimRange(x, low, high interface{}) float64 {
> >    var fx, flow, fhigh float64
> >    switch v := x.(type) {
> >    case int:                   //OK
> >    case int8:
> >    case int16:
> >    case int32:
> >    case float32:
> >    case float64:
> >       return float64(v)       //OK
> >
> >    default:
> >       return math.NaN()
> >    }
> >
> >    switch v := x.(type) {
> >    case int,int8,int16,int32,float32,float64:
> >       return float64(v)       //Error: cannot convert v (type
> > interface {}) to type float64: need type assertion
> >    default:
> >       return math.NaN()
> >    }
> >
> >     a :=1
> >    switch a {
> >    case 1,2:                    //OK
> >       println("1,2")
> >    }
> >
> >    return math.Max(math.Min(fx, fhigh), flow)
> > }
> >
> >
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to