douju2474 2016-02-06 19:43
浏览 25
已采纳

Golang坚持认为包作用域函数具有特定类型

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
", 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.

  • 写回答

1条回答 默认 最新

  • dongluanjie8678 2016-02-06 20:05
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?