英文:
Golang insist that package-scoped function has a particular type
问题
如果我有一个类型别名FooType
和一个函数Foo
,有没有办法坚持Foo
是FooType
的实例。我想要一个明确的FooType
,这样我就可以在类型切换中使用它。
如果可以的话,我不想使用var
和函数字面量,因为这样当我尝试重新定义一个函数时就不会出错。
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))
}
这样做的动机是我有两种类型的过滤器,可以处理文本流或结构化对象。
// 从通道处理项目
func filter1(in <-chan interface{}, out chan<- chan interface{}) {
for item := range in {
out <- doStuff(item)
}
}
// 从Scanner处理项目
func filter2(scanner *Scanner, out chan<- chan interface{}) {
for scanner.Scan() {
out <- doStuff(scanner.Text())
}
}
我希望能够编写一个函数,它接受一个*exec.Cmd
和一个过滤器数组,并将它们组合起来。
英文:
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.
答案1
得分: 2
你可以将Foo
赋值给一个匿名变量FooType
,如果类型不匹配,编译器会报错,例如:
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() {
}
注意,var _ FooType = NotAFoo
会导致错误。如果将其注释掉,程序将正常运行。Playground链接
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论