CodexBloom - Programming Q&A Platform

How to implement guide with trait bounds in rust when implementing a generic function with multiple types

👀 Views: 417 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-08
rust generics traits Rust

I've been struggling with this for a few days now and could really use some help. I've encountered a strange issue with I've tried everything I can think of but I'm relatively new to this, so bear with me. I'm working with a frustrating scenario while trying to implement a generic function that takes a reference to a vector of different types that implement a specific trait. My goal is to create a function that can accept either `i32` or `f64` values and print them. However, I'm working with a compiler behavior saying that the trait bound isn't satisfied. Here's the relevant code snippet: ```rust trait Printable { fn print_value(&self); } impl Printable for i32 { fn print_value(&self) { println!("Integer: {}", self); } } impl Printable for f64 { fn print_value(&self) { println!("Float: {}", self); } } fn print_values<T: Printable>(values: Vec<T>) { for value in values { value.print_value(); } } fn main() { let int_values: Vec<i32> = vec![1, 2, 3]; let float_values: Vec<f64> = vec![1.1, 2.2, 3.3]; print_values(int_values); print_values(float_values); } ``` When I compile this code, I receive the following behavior: ``` behavior[E0308]: mismatched types --> src/main.rs:18:5 | 18| print_values(int_values); | ^^^^^^^^^^^^^^^^^^^^^^^^^ expected struct `Vec<_>`, found struct `Vec<i32>` ``` I've tried using enums to wrap the different types, but that complicates the solution and requires more boilerplate code. Is there a way to maintain type safety while allowing for different types that share a common trait? I'm using Rust 1.60.0. Any pointers or best practices for this scenario would be greatly appreciated! This is happening in both development and production on Debian. What's the best practice here?