Questions tagged [traits]

In computer programming, a trait is a collection of methods, used as a "simple conceptual model for structuring object oriented programs"

Filter by
Sorted by
Tagged with
0 votes
1 answer
46 views

Implementing a generic function for a trait, which can operate on different number types

Is there a better way to implement a common conversion function over primitive number types? I've been struggling to create a more generic version of a trait, that converts a LE byte stream to ...
Jeff's user avatar
  • 1
2 votes
0 answers
40 views

Rust - object-safety rules are unclear - serde dyn serialize and deserialize [duplicate]

I'm attempting to do dynamic dispatch on a trait which allows for both serialization and de-serialization. Specifically: // [dependencies] // erased-serde = "0.3.31" // serde = { version= &...
jagprog5's user avatar
  • 101
1 vote
1 answer
44 views

How can I downcast to MyStruct and access method impl'd by Arc<Mutex<MyStruct>>? [duplicate]

I'm trying to do some testing against an existing implementation, which I cannot change for the testing purposes. For the test to work, I need to cast a dyn Thing into a RealThing. The catch is that ...
danda's user avatar
  • 609
0 votes
1 answer
29 views

"Blanket implementations" returning error in Rust

I made a Trait: pub trait DimenBasics { // --snip-- fn get_value(&self) -> f64; fn get_unit(&self) -> String; fn verified_add(&self, other: &Self) -> Result&...
Deadputo2024's user avatar
1 vote
1 answer
43 views

Trait to optionally dereference a reference to a Copy object?

I'm implementing a function that takes a list of elements by value, but I'll need to perform two passes over the list. The first pass computes some value over the input data (without modifying the ...
Bernard's user avatar
  • 5,299
0 votes
0 answers
44 views

Impl trait method on generic and vec of generic within a struct

I'm trying to implement the approx crate traits for a struct and it's fine with the values that are f64, but I don't know how to implement for the Vec values. The struct is pub struct Body<T> { ...
thefrollickingnerd's user avatar
4 votes
2 answers
59 views

What are the rules for coercing values to trait objects?

Consider the following Rust code: #[derive(Debug, Clone, Copy)] struct Struct; trait Trait {} impl Trait for Struct {} fn f() { // Why does this coerce to the target type (Result<Box<dyn ...
RBF06's user avatar
  • 2,169
11 votes
1 answer
499 views

prevent a trait function from being implemented by other struct

I just build a trait Bar with 2 functions (alpha() with implementation and beta() with only interfaces), and I hope the struct who implement Bar implements only beta(), and never implement their own ...
Rahn's user avatar
  • 4,975
0 votes
1 answer
37 views

Rust trait with multiple members, implemented by default, that depend on each other

Suppose I want to introduce a trait with 2 methods, that are dependent on each other in the sense, that one of them can be implemented by default using another. For example: use std::io; trait ...
Serhii Ch's user avatar
1 vote
1 answer
57 views

Upcasting trait in an option field

I am just learning Rust and have some issues with upcasting a trait ref inside an option. I want to pass it as ref to reduce the overhead. The basic idea is as follows: I have some objects (children) ...
Sapp's user avatar
  • 31
0 votes
1 answer
93 views

Implement interface for all types implementing another interface C#

Is it possible to implement an interface for all types implementing another interface in C#? For example, interface A { void foo(); } interface B { void bar(); } Now I want to provide an ...
Jack Maloney's user avatar
0 votes
1 answer
40 views

Implement trait on all unsigned integers through a macro

I've been writing a data storage module as a technical exercise to get a handle on some fundamental Rust, but I'm running into some problems implementing a trait to translate different types to and ...
Snowfallen's user avatar
1 vote
1 answer
87 views

Rust Function Returning a Generic Type

use std::marker::PhantomData; fn main() { pub type KG = u32; #[derive(Eq, PartialEq, Debug, Clone, Copy)] pub struct Pound(pub u32); impl From<Pound> for KG { fn from(...
Hakob Arshakyan's user avatar
0 votes
0 answers
63 views

Axum get request traits won't line up for generics

I've been testing out rust recently and decided to build a server using axum. I wanted to implement the endpoints in a generic form, so that I could create them easily in the future and to just play ...
kaweinh's user avatar
0 votes
1 answer
40 views

Mismatched types error when implementing a generic struct with a specific type parameter

I'm trying to implement a generic struct A1Implementation that takes a type parameter B which should implement the trait A1. However, when I try to create an instance of A1Implementation with a ...
Alberto's user avatar
  • 11
0 votes
3 answers
82 views

Rust Generics with Default Trait Implementations

I'm working on a Rust project where I have defined several traits (A1, A2, and A3) with multiple implementations for each trait. I also have a struct Algo that takes generics based on these traits. I ...
Alberto's user avatar
  • 11
0 votes
1 answer
60 views

How to call an inherited method from trait in Rust

pub mod stuff { pub trait Clone2: Clone {} impl<T: Clone> Clone2 for Vec<T> {} } fn main() { let x: Vec<u32> = Default::default(); let _ = stuff::Clone2::clone(&...
Cecile's user avatar
  • 1,613
0 votes
0 answers
49 views

How do I get the type of a variable behind a &dyn Trait?

In this following example I try printing out the type of both variable x and y (both with type Foo and Foo implements trait Bar). But when passed into a funtion print_name(), x is passed as &Foo ...
Rahn's user avatar
  • 4,975
1 vote
1 answer
42 views

Default generic type parameter not inferred in struct

I have a generic struct Test with a default generic type parameter implementing a trait. Here's my code: pub trait Implementation { fn test(); } pub struct FirstImpl; impl Implementation for ...
Alberto's user avatar
  • 11
1 vote
0 answers
50 views

Is it possible to define a function with callable parameter, where callable has unspecified number of arguments?

Let's say I have trait like this: trait Task<T> { fn solve(&self, func: fn(T) -> T) -> T; } That setup allows to pass function only like: fn solution(n: i32) -> i32{n} But i ...
Archirk's user avatar
  • 475
2 votes
1 answer
56 views

cannot implement generic fn for integer types

I am experienced in C++ and started to play around with rust. Trying to implement some simple generic functions, I got stuck with the following problem: use std::ops::BitAnd; use std::cmp::Eq; fn ...
user52366's user avatar
  • 1,097
0 votes
2 answers
55 views

Filter vector by element type

Is there a way to implement the function below? trait X {} struct A; struct B; impl X for A {} impl X for B {} /// Only keep elements of type A fn filter(list: Vec<Box<dyn X>>) -> ...
Lomírus's user avatar
4 votes
1 answer
80 views

Why don't Deref-like traits compose?

In this code, MyDeref matches the definition of Deref from the standard library, and MemoryView (simplified from a more complicated example) almost does too. pub trait MyDeref { type Target: ?...
apt1002's user avatar
  • 1,051
0 votes
1 answer
47 views

Use default value for Scala trait or abstract class in a case class that implements it

Is there a way to get a version of this code to use the default value defined in the trait? trait A { // alternately `abstract class A` def x: String def y: Int = 1 } final case class B(x: ...
Michael K's user avatar
  • 2,218
1 vote
1 answer
50 views

rustc cannot infer lifetime in trait implementations

I have the following code: use anyhow; struct InnerValue; enum Value { Int(i32), Other(InnerValue), } impl TryFrom<&Value> for &InnerValue { type Error = anyhow::Error; ...
gust's user avatar
  • 888
0 votes
1 answer
25 views

Scala Issue with Mixin Traits and Conflicting Members

I have the following setup for ms Scala test where I have a trait that looks like this: trait CPODBTestContainerSpec extends AnyFlatSpecLike with TestContainerForAll { .... .... } abstract class ...
joesan's user avatar
  • 14.3k
0 votes
0 answers
44 views

How to use multipart/form-data with hyper server and multer in Rust?

Currently I am trying to make file uploads to my web server - built on top of hyper - work. For that a request with multipart/form-data is sent to it. Since hyper is using struct Incoming on the 1.0.0-...
Florian's user avatar
  • 31
0 votes
0 answers
32 views

How do I expose an imported trait from the struct that derives it? [duplicate]

I have a file called my_args.rs and it goes something like this. use clap::Parser; #[derive(Parser, Debug)] #[command(author, version, about)] struct MyArgs(){ ... } and in main.rs use crate::...
subtea's user avatar
  • 1
0 votes
2 answers
68 views

Rust From/Into traits not working as expected

I'm having some problems understanding the behavior of the Into trait. I'm playing with the example in chapter 6.1 of "Rust by Example" and the behavior is not what I expected: use std::...
boogie's user avatar
  • 357
0 votes
0 answers
13 views

How to use @default trait?

I am new to smithy. I have a smithy structure: namespace example structure Identity { @required name: String @default(30.0) age: Double } structure Address { @required ...
lakshmiravali rimmalapudi's user avatar
-1 votes
1 answer
63 views

The source code on Rust Book Chapter 17 may be wrong

Initially I use this tutorial as reference for some practice code. After a few hours of troubleshooting I just plainly tried the code on that page as is. https://doc.rust-lang.org/book/ch17-02-trait-...
jeremyvillalobos's user avatar
1 vote
1 answer
96 views

Why does compiler say Hash is not implemented when I put a HashMap in my struct? [duplicate]

I'm trying to use a HashMap in a very basic way in my struct and I'm confounded by this error ... what am I missing? error[E0277]: the trait bound `HashMap<&str, &T>: Hash` is not ...
user10658782's user avatar
4 votes
1 answer
94 views

expected associated type, found type parameter

I faced an issue wit associated types... I found similar questions on SO, like these ones: Expected type parameter, found opaque type Matching a generic parameter to an associated type in an impl ...
zoryamba's user avatar
  • 338
0 votes
1 answer
82 views

Dealing with unknown mutability in rust

I'm having trouble understanding when to use mutable references as opposed to immutable references in traits. The following example for a Visitor implementation is taken from Rust Design Patterns: mod ...
Schottky's user avatar
  • 1,591
2 votes
1 answer
63 views

How to pass a struct implementing multiple traits to a function accepting those traits as &mut?

I'm dealing with a problem that can be simplified to the following code. The result is error[E0499]: cannot borrow *dog as mutable more than once at a time.. The origin of the error is clear to me, ...
PWolf's user avatar
  • 43
0 votes
1 answer
46 views

How to get a mutable reference to the contents of the Box<dyn T>?

Say I have a trait: trait ReactorClient<S : Source + ?Sized> { fn get_source(&self) -> S; } And a method that accepts Box<dyn ReactorClient>: fn register<S : Source + ?Sized&...
sad2k's user avatar
  • 11
0 votes
0 answers
49 views

How to implement a trait in Rust which modifies a field of self? [duplicate]

So how to do this: pub trait Thing { fn do_stuff(&mut self) { self.some_field = true; } } This won't compile because self.some_field is not defined. But the users of this trait ...
user2297996's user avatar
  • 1,414
0 votes
1 answer
20 views

Passing ChartContext in Rust

I'm trying to refactor out some repetitive plotting code in rust, but I'm running into a problem passing around the chart context. The function that I've written is below. pub fn plot<DB: ...
rprospero's user avatar
  • 913
0 votes
1 answer
59 views

Extend TryFrom to use a generic error type

I am attempting to use TryFrom to convert types, except that I would like to use a generic error type. How can I extend TryFrom to cope with an additional generic error parameter? use core::convert::...
darkestelephant's user avatar
0 votes
0 answers
57 views

Why do I get "type parameter `T` must be used as the type parameter for some local type" when creating a blanket implementation? [duplicate]

I'm trying to create a blanket implementation for all things that implement my Cookie trait, I want to implement ordering on self.value(), pub trait Cookie: std::fmt::Debug { fn name(&self) -&...
Evan Carroll's user avatar
0 votes
0 answers
49 views

How do I add a conditional constraint in smithy?

struct Car { @required CarName: String BMWSerialNumber: String } In above example, how could I enforce BMWSerialNumber to be required, only if CarName == "BMW"? I tried to add ...
dwh's user avatar
  • 1
1 vote
0 answers
60 views

How can I put a bound on an associated type of a generic method's trait bound in a trait with its own associated type?

I'm trying to figure out why the following won't compile. (playground) pub trait Foo { type FooType; fn foo<E>(x: Self::FooType) -> E where E: TryFrom<Self::FooType>...
Jari Maijenburg's user avatar
0 votes
0 answers
27 views

Different behaviours in the same function based on trait properties until specialization is stabilized?

I have the following problem. I want to write a generic function that process some geometry. The geometry may, or may not have normals. If it has defined normals, it should use one set of ...
Makogan's user avatar
  • 8,501
0 votes
1 answer
61 views

How can I avoid a conflicting implementation when creating a default trait implementation?

I am trying to create a default implementation for a trait in Rust along with one only available for certain types. Lets say I have this rust code here: trait Foo { fn function(); } impl<T> ...
v22's user avatar
  • 15
-1 votes
1 answer
48 views

Specify trait as enum variant value?

I have a type 'A', and various traits that define behaviours that can be done to A. struct A { pub foo: String; ... etc } trait BigChange { fn big_change(a: A) -> A } trait SmallChange {...
mozboz's user avatar
  • 1,077
0 votes
2 answers
72 views

Why can't I use U::from with T: Into<U> constraint?

I want to have a simple types conversions and I think the code should look like this: struct Celsius(f64); struct Fahrenheit(f64); impl From<Celsius> for Fahrenheit { fn from(c: Celsius) -&...
kik3r's user avatar
  • 43
5 votes
2 answers
142 views

How does boxing a trait affect lifetime of parameters passed to it ? (with a very specific example)

Here is a very simple but specific example that produces a compilation error I cannot understand: use std::path::Path; trait MyTrait<T> { fn my_func(&self, t: T); } struct MyImpl {} ...
fruphon's user avatar
  • 51
0 votes
2 answers
58 views

Why is the type alias required when implementing the `std::ops::Add` trait?

I exercised coding in Rust using the Rust By Practice book. I have encountered an example where I got a little bit confused. The following code is a revised version of the 4th exercise in the Traits ...
Péter Szilvási's user avatar
-2 votes
1 answer
51 views

How to disambiguate between function calls via trait function impl and struct impl in Rust? [duplicate]

The example code below demonstrates implementation of a trait for two structs, as well as a "native?" impl for functions with the same name for the two structs directly. (Hope that makes ...
FreelanceConsultant's user avatar
1 vote
1 answer
62 views

Implement a rust function that only accepts types that possess a certain method

I want to create a function that only accepts types that possess a certain method. For example, I know that the f32 and f64 primitive types possess a log10 method, and I therefore want a function that ...
Matt Pitkin's user avatar
  • 4,700

1
2 3 4 5
70