casting a generic (interface) to a type when all possible types have same methods

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

casting a generic (interface) to a type when all possible types have same methods

问题

使用以下方法:

x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey)

从定义上看,这里的publicKey和privateKey都是类型为'any'的。在编译时,我不知道用户会提供哪种类型的密钥 - 这似乎是可以接受的,因为我可以传递任何一种。

然而,我在处理any类型到这两种密钥类型之一时遇到了困难。

在我意识到可能有问题之前,我已经做到了这一点:

	var privKey any
	switch priv.(type) {
		case *ecdsa.PrivateKey:
			privKey = priv.(*ecdsa.PrivateKey)
		case *rsa.PrivateKey:
			privKey = priv.(*rsa.PrivateKey)
		default:
			return nil, nil, errors.New("no valid key type passed")

	}
	der, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, priv)

我可以将CreateCertificate调用移到各个case内部,但这似乎是重复的代码。正确的做法是什么?

英文:

Take the method:

x509.CreateCertificate(rand.Reader, &template, &template, publicKey, privateKey)

looking at the defitiniton, both publicKey and privateKey here are type 'any'. I don't know at compile time which type of key a user will provide - and that seems fine as I can pass either in.

However, I am struggling with the handling of the any to either of these types of keys.

This was where I got to before I realised I might have a problem:

	var privKey any
	switch priv.(type) {
		case *ecdsa.PrivateKey:
			privKey = priv.(*ecdsa.PrivateKey)
		case *rsa.PrivateKey:
			privKey = priv.(*rsa.PrivateKey)
		default:
			return nil, nil, errors.New("no valid key type passed")

	}
	der, err := x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, priv)

I could move the CreateCertificate call inside the cases, but that seems copypasta. Whats the correct way to do this?

答案1

得分: 2

正如评论中指出的那样,解决方案是私钥都遵循我忽略的crypto.Signer接口。

因此可以执行priv.(crypto.Signer).Public()

英文:

As pointed out in the comments, the solution is that the private keys both adhere to the interface crypto.Signer which I missed.

Therefore can do priv.(crypto.Signer).Public()

huangapple
  • 本文由 发表于 2023年3月30日 18:17:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/75886938.html
匿名

发表评论

匿名网友

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

确定