Search code examples
gotypestype-assertion

Go change from interface to required type


I have this method where I receive an int64 param. The parameter is used in some areas and then is supposed to be passed down to another method (from an external lib) that expects a different type: type AcctInterimInterval uint32

I tried converting it to a uint32 but the script complains about it: invalid type assertion: ... (non-interface type int on left).

I also tried converting it to AcctInterimInterval but this time with a different error: interface conversion: interface {} is int, not main.AcctInterimInterval

Here's my test code so far:

package main

import (
    "fmt"
)

//  defined in some other lib
type AcctInterimInterval uint32

//  defined in some other lib
func test(value AcctInterimInterval){
    fmt.Println(value)
}

func main() {
    //  int received externally
    interval := 60

    var acctInterval interface{} = interval

    test(acctInterval.(AcctInterimInterval))
}

Associated playground: https://play.golang.org/p/tTW5J2FIAy3


Solution

  • Your acctInterval variable wraps an int value, so you can only type-assert an int from it:

    acctInterval.(int)
    

    Which then you can convert to AcctInterimInterval:

    test(AcctInterimInterval(acctInterval.(int)))
    

    Try it on the Go Playground.