惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Security Archives - TechRepublic
Security Archives - TechRepublic
Project Zero
Project Zero
K
Kaspersky official blog
G
Google Developers Blog
T
Threat Research - Cisco Blogs
T
The Blog of Author Tim Ferriss
Cyberwarzone
Cyberwarzone
Y
Y Combinator Blog
Recorded Future
Recorded Future
Blog — PlanetScale
Blog — PlanetScale
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
Microsoft Security Blog
Microsoft Security Blog
H
Help Net Security
S
Schneier on Security
P
Palo Alto Networks Blog
H
Hacker News: Front Page
N
News and Events Feed by Topic
N
Netflix TechBlog - Medium
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
SecWiki News
SecWiki News
Cloudbric
Cloudbric
TaoSecurity Blog
TaoSecurity Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Hacker News
The Hacker News
C
Check Point Blog
L
LangChain Blog
腾讯CDC
小众软件
小众软件
T
Tenable Blog
Google DeepMind News
Google DeepMind News
GbyAI
GbyAI
L
LINUX DO - 最新话题
A
About on SuperTechFans
Google Online Security Blog
Google Online Security Blog
C
Cisco Blogs
Recent Announcements
Recent Announcements
Hacker News: Ask HN
Hacker News: Ask HN
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Vercel News
Vercel News
雷峰网
雷峰网
美团技术团队
D
DataBreaches.Net
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
F
Full Disclosure
博客园_首页

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
[Rust Guide] 10.4. Trait Pt.2 - Traits as Parameters and Return Types, Trait Bounds
SomeB1oody · 2026-04-27 · via DEV Community

If you find this helpful, please like, bookmark, and follow. To keep learning along, follow this series.

By the way, writing this article took even longer than writing the ownership chapter. Traits are truly a concept that is hard to understand.

10.4.1 Using Traits as Parameters

Let’s continue using the content from the previous article as the example:

pub trait Summary {
    fn summarize(&self) -> String;
}

pub struct NewsArticle {
    pub headline: String,
    pub location: String,
    pub author: String,
    pub content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

pub struct Tweet {
    pub username: String,
    pub content: String,
    pub reply: bool,
    pub retweet: bool,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}

Enter fullscreen mode Exit fullscreen mode

If we define a new function notify, which takes NewsArticle and Tweet as the two types and prints Breaking news!, followed by the return value of calling the summarize method from Summary on the parameter, there is a problem:

the function accepts two different struct types. How can we make the parameter work for two types?

Let’s think about it: what do these two structs have in common? Exactly—they both implement the Summary trait. Rust provides a solution for this situation:

pub fn notify(item: &impl Summary) {  
    println!("Breaking news! {}", item.summarize());  
}

Enter fullscreen mode Exit fullscreen mode

Just write the parameter type as impl some_trait. Since both of these structs implement the Summary trait, we write impl Summary. And because this function does not need ownership of the data, we write it as a reference: &impl Summary. If some other data type also implements Summary, it can be passed in as well.

The impl trait syntax is suitable for simple cases. For more complex cases, trait bound syntax is usually used.

Using the same code, but written with trait bounds:

pub fn notify<T: Summary>(item: &T) {  
    println!("Breaking news! {}", item.summarize());  
}

Enter fullscreen mode Exit fullscreen mode

These two forms are equivalent.

However, this simple example does not show the advantages of trait bounds very well. Let’s look at another example. Suppose I want to design a new notify1 function. It takes two parameters, and the content after Breaking news! is the return value of calling summarize on each parameter.

Trait-bound version:

pub fn notify1<T: Summary>(item1: &T, item2: &T) {  
    println!("Breaking news! {} {}", item1.summarize(), item2.summarize());  
}

Enter fullscreen mode Exit fullscreen mode

impl trait version:

pub fn notify1(item1: &impl Summary, item2: &impl Summary) {  
    println!("Breaking news! {} {}", item1.summarize(), item2.summarize());  
}

Enter fullscreen mode Exit fullscreen mode

Clearly, the former function signature is easier to write and more intuitive than the latter.

In fact, impl trait is just syntax sugar for trait bounds, so it is understandable that it is not suitable for complex cases.

So what if the notify function needs its parameter to implement both the Display trait and the Summary trait? In other words, how do you write two or more trait bounds?

Example:

pub fn notify_with_display<T: Summary + std::fmt::Display>(item: &T) {  
    println!("Breaking news! {}", item);  
}

Enter fullscreen mode Exit fullscreen mode

Use + to connect each trait bound.

Another point: because Display is not in the prelude, when writing it you need to spell out its path. You can also import Display at the top of the code first, like this: use std::fmt::Display. Then you can write Display directly in the trait bounds:

use std::fmt::Display;

pub fn notify_with_display<T: Summary + Display>(item: &T) {  
    println!("Breaking news! {}", item);  
}

Enter fullscreen mode Exit fullscreen mode

Don’t forget that impl trait is also syntax sugar, and in that syntax sugar you also connect trait bounds with +:

use std::fmt::Display;

pub fn notify_with_display(item: &(impl Summary + Display)) {  
    println!("Breaking news! {}", item);  
}

Enter fullscreen mode Exit fullscreen mode

This form has one drawback: if there are too many trait bounds, the large amount of constraint information will reduce the readability of the function signature. To solve this, Rust provides an alternative syntax: write the trait bounds after the function signature using a where clause.

Here is the ordinary syntax for multiple trait bounds:

use std::fmt::Display;  
use std::fmt::Debug;

pub fn special_notify<T: Summary + Display, U: Summary + Debug>(item1: &T, item2: &U) {  
    println!("Breaking news! {} and {}", item1.summarize(), item2.summarize());  
}

Enter fullscreen mode Exit fullscreen mode

The same code rewritten with a where clause:

use std::fmt::Display;  
use std::fmt::Debug;

pub fn special_notify<T, U>(item1: &T, item2: &U)   
where  
    T: Summary + Display,  
    U: Summary + Debug,  
{  
    println!("Breaking news! {} and {}", item1.summarize(), item2.summarize());  
}

Enter fullscreen mode Exit fullscreen mode

This syntax is very similar to C#.

10.4.2 Using Traits as Return Types

Just like using traits as parameters, using traits as return values can also use impl trait. For example:

fn returns_summarizable() -> impl Summary {  
    Tweet {  
        username: String::from("horse_ebooks"),  
        content: String::from(  
            "of course, as you probably already know, people",  
        ),  
        reply: false,  
        retweet: false,  
    }  
}

Enter fullscreen mode Exit fullscreen mode

This syntax has a drawback: if the return type implements a certain trait, then you must ensure that all possible return values of this function/method are only one type. That is because the impl form has some limitations in how it works, which is why Rust does not support it in every case. But Rust does support dynamic dispatch, which will be covered later.

For example:

fn returns_summarizable(flag:bool) -> impl Summary {  
    if flag {  
        Tweet {  
        username: String::from("horse_ebooks"),  
        content: String::from(  
            "of course, as you probably already know, people",  
        ),  
        reply: false,  
        retweet: false,  
        }  
    } else {  
        NewsArticle {  
            headline: String::from("Penguins win the Stanley Cup Championship!"),  
            location: String::from("Pittsburgh, PA, USA"),  
            author: String::from("Iceburgh, Scotland"),  
            content: String::from(  
                "The Pittsburgh Penguins once again are the best \  
                hockey team in the NHL.",  
            ),  
        }  
    }  
}

Enter fullscreen mode Exit fullscreen mode

There are two possible return types depending on the value of flag: Tweet and NewsArticle. At that point, the compiler will report an error:

error[E0308]: `if` and `else` have incompatible types
  --> src/lib.rs:42:9
   |
32 | /       if flag {
33 | | /         Tweet {
34 | | |         username: String::from("horse_ebooks"),
35 | | |         content: String::from(
36 | | |             "of course, as you probably already know, people",
...  | |
39 | | |         retweet: false,
40 | | |         }
   | | |_________- expected because of this
41 | |       } else {
42 | | /         NewsArticle {
43 | | |             headline: String::from("Penguins win the Stanley Cup Championship!"),
44 | | |             location: String::from("Pittsburgh, PA, USA"),
45 | | |             author: String::from("Iceburgh, Scotland"),
...  | |
49 | | |             ),
50 | | |         }
   | | |_________^ expected `Tweet`, found `NewsArticle`
51 | |       }
   | |_______- `if` and `else` have incompatible types
   |
help: you could change the return type to be a boxed trait object
   |
31 | fn returns_summarizable(flag:bool) -> Box<dyn Summary> {
   |                                       ~~~~~~~        +
help: if you change the return type to expect trait objects, box the returned expressions
   |
33 ~         Box::new(Tweet {
34 |         username: String::from("horse_ebooks"),
...
39 |         retweet: false,
40 ~         })
41 |     } else {
42 ~         Box::new(NewsArticle {
43 |             headline: String::from("Penguins win the Stanley Cup Championship!"),
...
49 |             ),
50 ~         })
   |

Enter fullscreen mode Exit fullscreen mode

The error message says that the return types of if and else are incompatible, meaning they are not the same type.

Trait Bound Example

Do you still remember the code for comparing numbers that was mentioned in 10.2. Generics? I’ll paste it here:

fn largest<T>(list: &[T]) -> T{  
    let mut largest = list[0];  
    for &item in list{  
        if item > largest{  
            largest = item;  
        }  
    }  
    largest  
}

Enter fullscreen mode Exit fullscreen mode

I’ll also paste the error that occurred at that time:

error[E0369]: binary operation `>` cannot be applied to type `T`
 --> src/main.rs:4:17
  |
4 |         if item > largest{
  |            ---- ^ ------- T
  |            |
  |            T
  |
help: consider restricting type parameter `T`
  |
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> T{
  |             ++++++++++++++++++++++

Enter fullscreen mode Exit fullscreen mode

Now that we have learned traits, does your understanding of this code and its error message feel different?

Let’s start by analyzing the error message. The error says that the comparison operator > cannot be applied to type T. The help line below says to consider restricting type parameter T, and further down it gives the concrete approach: add std::cmp::PartialOrd after T (in the trait bound, you only need to write PartialOrd because it is in the prelude, so the full path is not needed). This is actually the trait used for comparisons. Try modifying it according to the hint:

fn largest<T: PartialOrd>(list: &[T]) -> T{  
    let mut largest = list[0];  
    for &item in list{  
        if item > largest{  
            largest = item;  
        }  
    }  
    largest  
}

Enter fullscreen mode Exit fullscreen mode

It still reports an error:

error[E0508]: cannot move out of type `[T]`, a non-copy slice
 --> src/main.rs:2:23
  |
2 |     let mut largest = list[0];
  |                       ^^^^^^^
  |                       |
  |                       cannot move out of here
  |                       move occurs because `list[_]` has type `T`, which does not implement the `Copy` trait
  |
help: if `T` implemented `Clone`, you could clone the value
 --> src/main.rs:1:12
  |
1 | fn largest<T: std::cmp::PartialOrd>(list: &[T]) -> T{
  |            ^ consider constraining this type parameter with `Clone`
2 |     let mut largest = list[0];
  |                       ------- you could clone this value
help: consider borrowing here
  |
2 |     let mut largest = &list[0];
  |                       +

Enter fullscreen mode Exit fullscreen mode

But the error is different this time: the element cannot be moved out of list, because T in list does not implement the Copy trait. The help below says that if T implements the Clone trait, consider cloning the value. There is also another help below that suggests borrowing.

Based on the above information, there are three solutions:

  • Add the Copy trait to the generic type
  • Use cloning, which means adding the Clone trait to the generic type
  • Use borrowing

Which solution should we choose? It depends on your needs. I want this function to handle collections of numbers and characters. Since numbers and characters are stored on the stack, they both implement the Copy trait, so it is enough to add Copy to the generic type:

fn largest<T: PartialOrd + Copy>(list: &[T]) -> T{    
    let mut largest = list[0];    
    for &item in list{    
        if item > largest{    
            largest = item;    
        }    
    }    
    largest    
}  

fn main() {  
    let number_list = vec![34, 50, 25, 100, 65];  
    let result = largest(&number_list);  
    println!("The largest number is {}", result);  

    let char_list = vec!['y', 'm', 'a', 'q'];  
    let result = largest(&char_list);  
    println!("The largest char is {}", result);  
}

Enter fullscreen mode Exit fullscreen mode

Output:

The largest number is 100
The largest char is y

Enter fullscreen mode Exit fullscreen mode

What if I want this function to compare a String collection? Since String is stored on the heap, it does not implement the Copy trait, so the idea of adding Copy to the generic type does not work.

Then try cloning, which means adding the Clone trait to the generic type:

fn largest<T: PartialOrd + Clone>(list: &[T]) -> T{    
    let mut largest = list[0].clone();    
    for &item in list.iter() {    
        if item > largest{    
            largest = item;    
        }    
    }    
    largest    
}  

fn main() {  
    let string_list = vec![String::from("dev1ce"), String::from("Zywoo")];  
    let result = largest(&string_list);  
    println!("The largest string is {}", result);  
}

Enter fullscreen mode Exit fullscreen mode

Output:

error[E0507]: cannot move out of a shared reference
 --> src/main.rs:3:18
  |
3 |     for &item in list.iter() {  
  |          ----    ^^^^^^^^^^^
  |          |
  |          data moved here
  |          move occurs because `item` has type `T`, which does not implement the `Copy` trait
  |
help: consider removing the borrow
  |
3 -     for &item in list.iter() {  
3 +     for item in list.iter() {  
  |

Enter fullscreen mode Exit fullscreen mode

The error says that data cannot be moved because this form requires Copy, which String does not provide. What should we do?

Then do not move the data; do not use pattern matching. Remove the & in front of item, so item changes from T to an immutable reference &T. Then use the dereference operator * during comparison to dereference &T back to T and compare it with largest (the code below uses this approach), or add & in front of largest to make it &T. In short, the two values being compared must have the same type:

fn largest<T: PartialOrd + Clone>(list: &[T]) -> T{    
    let mut largest = list[0].clone();    
    for item in list.iter() {    
        if *item > largest{    
            largest = item.clone();    
        }    
    }    
    largest    
}

fn main() {  
    let string_list = vec![String::from("dev1ce"), String::from("Zywoo")];  
    let result = largest(&string_list);  
    println!("The largest string is {}", result);  
}

Enter fullscreen mode Exit fullscreen mode

Remember that T does not implement the Copy trait, so when assigning to largest, you need to use the clone method.

Output:

The largest string is dev1ce

Enter fullscreen mode Exit fullscreen mode

This form is written this way because the return value is T. If you change the return value to &T, then cloning is no longer needed:

fn largest<T: PartialOrd>(list: &[T]) -> &T{      
    let mut largest = &list[0];      
    for item in list.iter() {      
        if item > largest{      
            largest = item;      
        }      
    }      
    largest      
}  

fn main() {  
    let string_list = vec![String::from("dev1ce"), String::from("Zywoo")];  
    let result = largest(&string_list);  
    println!("The largest string is {}", result);  
}

Enter fullscreen mode Exit fullscreen mode

But remember that when initializing largest, you must set it to &T, so you need to add & in front of list[0] to make it a reference. Also, when comparing, you cannot use the method of dereferencing item; instead, you need to add & in front of largest.

10.4.3 Conditionally Implementing Methods with Trait Bounds

If you use trait bounds on an impl block with generic type parameters, you can conditionally implement methods for types that implement specific traits.

For example:

use std::fmt::Display;  

struct Pair<T> {  
    x: T,  
    y: T,  
}  

impl<T> Pair<T> {  
    fn new(x: T, y: T) -> Self {  
        Self { x, y }  
    }  
}  

impl<T: Display + PartialOrd> Pair<T> {  
    fn cmp_display(&self) {  
        if self.x >= self.y {  
            println!("The largest member is x = {}", self.x);  
        } else {  
            println!("The largest member is y = {}", self.y);  
        }  
    }  
}

Enter fullscreen mode Exit fullscreen mode

No matter what the concrete type of T is, the new function will always exist on Pair. But the cmp_display method exists only when T implements both Display and PartialOrd.

You can also conditionally implement one trait for any type that implements another trait. Implementing a trait for all types that satisfy a trait bound is called a blanket implementation.

Take the standard library’s to_string function as an example:

impl<T: Display> ToString for T {
    // ......
}

Enter fullscreen mode Exit fullscreen mode

This means that ToString is implemented for all types that satisfy the Display trait, which is what a blanket implementation is: any type that implements Display can call methods on ToString.

Using an integer as an example:

let s = 3.to_string();

Enter fullscreen mode Exit fullscreen mode

This works because i32 implements the Display trait, so it can call the to_string method from ToString.