只允许将指针传递给函数,而不是值。

huangapple go评论62阅读模式
英文:

Allow pass to func only pointer, not values

问题

我想要限制函数只接受指向结构体的指针,而不接受具体的值。这种做法可行吗?

我想要实现的效果是:

Foo(&Bar{}) // 允许
Foo(Bar{}) // IDE/编译错误

目前我使用的函数签名是func Foo(bar any),它允许传递给函数任何接口和类型,这在某些情况下可能会引起问题。

可以传递给该函数的类型数量应该没有限制,而且我不想使用特定的接口等。也许可以通过泛型来实现?但我不确定如何正确地做到这一点。

我使用的是 Go 1.18 版本。

英文:

I want to allow pass to func only pointer to a struct, restrict values. Is it possible?

What I want to do:

Foo(&Bar{}) // allowed
Foo(Bar{}) // IDE/compilation error

Actually i'm using signature like func Foo(bar any) which allows pass to the function any interface and type, of course, so in some cases it can cause problems.

Amount of types, which can passed to this function is should be not limited, and I don't want to use specific interface etc. Maybe this can be achieved with generics? But I'm not sure how to do it correctly.

I'm use go 1.18.

答案1

得分: 3

是的,你可以像这样使用泛型:

func Foo[T any](t *T){

}
英文:

Yes you can use generics like this:

func Foo[T any](t *T){

}

</details>



huangapple
  • 本文由 发表于 2022年4月6日 20:40:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/71766919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定