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 关于#python#的问题,请各位专家解答!
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备