traits

What is the advantage of using abstract classes instead of traits?

♀尐吖头ヾ 提交于 2019-11-26 04:29:02
问题 What is the advantage of using an abstract class instead of a trait (apart from performance)? It seems like abstract classes can be replaced by traits in most cases. 回答1: I can think of two differences Abstract classes can have constructor parameters as well as type parameters. Traits can have only type parameters. There was some discussion that in future even traits can have constructor parameters Abstract classes are fully interoperable with Java. You can call them from Java code without

How do I use integer number literals when using generic types?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-26 04:28:36
问题 I wanted to implement a function computing the number of digits within any generic type of integer. Here is the code I came up with: extern crate num; use num::Integer; fn int_length<T: Integer>(mut x: T) -> u8 { if x == 0 { return 1; } let mut length = 0u8; if x < 0 { length += 1; x = -x; } while x > 0 { x /= 10; length += 1; } length } fn main() { println!(\"{}\", int_length(45)); println!(\"{}\", int_length(-45)); } And here is the compiler output error[E0308]: mismatched types --> src

How do I return an instance of a trait from a method?

我是研究僧i 提交于 2019-11-26 04:27:13
问题 I\'m trying to create a function that returns an instance of the Shader trait. Here is my drastically simplified code: trait Shader {} struct MyShader; impl Shader for MyShader {} struct GraphicsContext; impl GraphicsContext { fn create_shader(&self) -> Shader { let shader = MyShader; shader } } fn main() {} However I receive the following error: error[E0277]: the trait bound `Shader + \'static: std::marker::Sized` is not satisfied --> src/main.rs:10:32 | 10 | fn create_shader(&self) ->

I implemented a trait for another trait but cannot call methods from both traits

穿精又带淫゛_ 提交于 2019-11-26 04:00:07
问题 I have a trait called Sleep : pub trait Sleep { fn sleep(&self); } I could provide a different implementation of sleep for every struct, but it turns out that most people sleep in a very small number of ways. You can sleep in a bed: pub trait HasBed { fn sleep_in_bed(&self); fn jump_on_bed(&self); } impl Sleep for HasBed { fn sleep(&self) { self.sleep_in_bed() } } If you\'re camping, you can sleep in a tent: pub trait HasTent { fn sleep_in_tent(&self); fn hide_in_tent(&self); } impl Sleep for

How do I implement the Add trait for a reference to a struct?

旧时模样 提交于 2019-11-26 02:57:56
问题 I made a two element Vector struct and I want to overload the + operator. I made all my functions and methods take references, rather than values, and I want the + operator to work the same way. impl Add for Vector { fn add(&self, other: &Vector) -> Vector { Vector { x: self.x + other.x, y: self.y + other.y, } } } Depending on which variation I try, I either get lifetime problems or type mismatches. Specifically, the &self argument seems to not get treated as the right type. I have seen

How to get a reference to a concrete type from a trait object?

只愿长相守 提交于 2019-11-26 01:36:19
问题 How do I get Box<B> or &B or &Box<B> from the a variable in this code: trait A {} struct B; impl A for B {} fn main() { let mut a: Box<dyn A> = Box::new(B); let b = a as Box<B>; } This code returns an error: error[E0605]: non-primitive cast: `std::boxed::Box<dyn A>` as `std::boxed::Box<B>` --> src/main.rs:8:13 | 8 | let b = a as Box<B>; | ^^^^^^^^^^^ | = note: an `as` expression can only be used to convert between primitive types. Consider using the `From` trait 回答1: There are two ways to do

Why can impl trait not be used to return multiple / conditional types?

痞子三分冷 提交于 2019-11-26 00:56:06
问题 I\'m trying to get a random number generator. Since OsRng::new() can fail, I\'d like to fall back to thread_rng() if I have to: extern crate rand; // 0.6.5 use rand::{rngs::OsRng, thread_rng, RngCore}; fn rng() -> impl RngCore { match OsRng::new() { Ok(rng) => rng, Err(e) => thread_rng(), } } However, I get this error message which I cannot understand: error[E0308]: match arms have incompatible types --> src/lib.rs:6:5 | 6 | / match OsRng::new() { 7 | | Ok(rng) => rng, 8 | | Err(e) => thread

What is the difference between self-types and trait subclasses?

柔情痞子 提交于 2019-11-26 00:12:09
问题 A self-type for a trait A : trait B trait A { this: B => } says that \" A cannot be mixed into a concrete class that does not also extend B \" . On the other hand, the following: trait B trait A extends B says that \"any (concrete or abstract) class mixing in A will also be mixing in B\" . Don\'t these two statements mean the same thing? The self-type seems to serve only to create the possibility of a simple compile-time error. What am I missing? 回答1: It is predominately used for Dependency

“Expected type parameter” error in the constructor of a generic struct

為{幸葍}努か 提交于 2019-11-25 23:15:08
问题 I am trying to store piston textures in a struct. struct TextureFactory<R> where R: gfx::Resources { block_textures: Vec<Rc<Texture<R>>>, } impl<R> TextureFactory<R> where R: gfx::Resources { fn new(window: PistonWindow) -> Self { let texture = Rc::new(gfx_texture::Texture::from_path( &mut *window.factory.borrow_mut(), \"assets/element_red_square.png\", Flip::None, &TextureSettings::new() ).unwrap()); let block_textures = Vec::new(); block_textures.push(texture); TextureFactory { block

How do I implement a trait I don&#39;t own for a type I don&#39;t own?

孤人 提交于 2019-11-25 22:45:22
问题 I wanted to implement the Shl trait for Vec , the code is below. This would make things like vec << 4 possible, which would be nice sugar for vec.push(4) . use std::ops::Shl; impl<T> Shl<T> for Vec<T> { type Output = Vec<T>; fn shl(&self, elem: &T) -> Vec<T> { self.push(*elem); *self } } fn main() { let v = vec![1, 2, 3]; v << 4; } The compilation fails with the following error: cannot provide an extension implementation where both trait and type are not defined in this crate [E0117] or type