Home Ask Login Register

Developers Planet

Your answer is one click away!

Gregory Nisbet February 2016

Golang insist that package-scoped function has a particular type

If I have a type synonym FooType and a function Foo is there a way to insist that Foo is an instance of FooType. I'd like an explicit FooType so I can use it in a type switch.

I don't want to use a var and function literal if I can avoid it because then I don't get an error when I attempt to redefine a function.

package main

import (
    "fmt"
    "reflect"
)

type FooType func(a int, b float64) float32

// foo happens to be of FooType, but this relationship isn't
// enforced by the compiler.
func Foo(a int, b float64) float32 {
    return 2.4
}

func main () {
    fmt.Printf("type of foo: %v\n", reflect.TypeOf(foo))
}

The motivation for this is I have two types of filters that can process streams of text or structured objects.

// process items from channel
function filter1(in <-chan interface{}, out chan<- chan interface{}) {
    for item := range in {
        out <- doStuff(item)
    }
}

// process items from Scanner
function filter2(scanner *Scanner, out chan<- chan interface{}) {
    for scanner.Scan() {
        out <- doStuff(scanner.Text())
    }
}

I'd like to be able to write a function that takes an *exec.Cmd and an array of filters and combines them.

Answers


Amit Kumar Gupta February 2016

You can assign Foo to an anonymous variable of type FooType which will the compiler will complain about if the type doesn't match, e.g.:

package main

type FooType func(a int, b float64) float32

func Foo(a int, b float64) float32 {
    return 2.4
}

func NotAFoo(a string, b bool) float32 {
    return 2.4
}

var _ FooType = Foo
var _ FooType = NotAFoo

func main() {
}

Note that the var _ FooType = NotAFoo blows up. If you comment it out, the program runs fine. Playground link

Post Status

Asked in February 2016
Viewed 3,543 times
Voted 11
Answered 1 times

Search




Leave an answer


Quote of the day: live life