Rust compiler complains that a type annotation is needed, but when it is added then it suddenly is not allowed!

Original code:

use p256::{SecretKey as EccPrivateKey, ecdsa::{SigningKey as EccSigningKey, Signature as EccSignature}, pkcs8::DecodePrivateKey};
fn create_signature_ecc<T>(private_key: &EccPrivateKey, message: &[u8]) -> Vec<u8> {
    EccSigningKey::from(private_key).sign_with_rng(&mut thread_rng(), message).to_vec()
}

Error:

type annotations needed
cannot infer type for type parameter S declared on the trait RandomizedSigner

The method from Struct ecdsa::SigningKey signature is:

impl<C> RandomizedSigner<Signature<C>> for SigningKey<C> {
/* ... */
fn sign_with_rng(&self, rng: &mut impl CryptoRngCore, msg: &[u8]) -> S

Code updated as requested:

fn create_signature_ecc<T>(private_key: &EccPrivateKey, message: &[u8]) -> Vec<u8> {
    EccSigningKey::from(private_key).sign_with_rng::<EccSignature>(&mut thread_rng(), message).to_vec()
}

Error:

method takes 0 generic arguments but 1 generic argument was supplied
impl Trait cannot be explicitly specified as a generic argument

How can I resolve this? :confused:

If it's a parameter on the trait, e.g. trait RandomizedSigner<S>, then you cannot provide it on the method like .sign_with_rng::<EccSignature>.

You can instead use the fully qualified syntax <Type as Trait>::method(self_arg, other_args...); in this case, it can also probably be shortened to just Trait::method(self_arg, other_args...).

So try something like

RandomizedSigner::<EccSignature>::sign_with_rng(&EccSigningKey::from(private_key), &mut thread_rng(), message).to_vec()

and tell us if that works.

6 Likes

This works :sunglasses:

use p256::{SecretKey as EccPrivateKey, ecdsa::{SigningKey as EccSigningKey, Signature as EccSignature, signature::RandomizedSigner as EccRandomizedSigner}, pkcs8::DecodePrivateKey};

fn _create_signature_ecc<T>(private_key: &EccPrivateKey, message: &[u8]) -> Vec<u8> {
    EccRandomizedSigner::<EccSignature>::sign_with_rng(&EccSigningKey::from(private_key), &mut thread_rng(), message).to_vec()
}

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.