Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

How to use generic traits? [Question] #235

Answered by 9prady9
BA8F0D39 asked this question in Q&A
Discussion options

pub fn addnum(a: &arrayfire::Array<arrayfire::FloatingPoint>
	,b: &arrayfire::Array<arrayfire::FloatingPoint>) -> arrayfire::Array<arrayfire::FloatingPoint> {
 a + b
}

I want to make a function that accepts the trait arrayfire::FloatingPoint and produces arrayfire::FloatingPoint. What modifications do I need to make it compile?

You must be logged in to vote

In that case, you should look at https://doc.rust-lang.org/rust-by-example/generics.html

fn foo<T>(arg: T) { ... } that is how you define a generic function. In this case, the generic type T is what reused for defining the generic type Array<> that is in turn used a arguments to the function.

Replies: 3 comments

Comment options

@BA8F0D39 I am not sure I understand your use case, the trait you mentioned is more like a contract checking so that only acceptable Array objects(Array is generic struct) are passed to the relevant functions.

Is this what you are trying to achieve ?

pub fn addnum(a: &arrayfire::Array<T>,b: &arrayfire::Array<T>) -> arrayfire::Array<T> 
where T: FloatingPoint {
 a + b
}
You must be logged in to vote
0 replies
Comment options

I am new to rust and the rust compiler says cannot find type T in this scope.
How would you define the trait T in this case to use arrayfire::FloatingPoint?

You must be logged in to vote
0 replies
Comment options

In that case, you should look at https://doc.rust-lang.org/rust-by-example/generics.html

fn foo<T>(arg: T) { ... } that is how you define a generic function. In this case, the generic type T is what reused for defining the generic type Array<> that is in turn used a arguments to the function.

You must be logged in to vote
0 replies
Answer selected by 9prady9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #235 on December 09, 2020 05:16.

AltStyle によって変換されたページ (->オリジナル) /