当实现to_sql时,Rust枚举变体应该首先被转换为&str,这可以通过实现MyEnum的Display来实现,以便在MyEnum变体和字符串之间进行映射。 use std::fmt::{Display, Formatter, Result }; impl Display for MyEnum { fn fmt(&self, f: &mut Formatter) -> Result { match self { MyEnum...
impl Display for Integers{ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", (*self as i32)) } } 针对带变量值的枚举类型,为其定义函数的作用将更大。比如我们前面定义的统一的8位有符号和无符号整数的枚举值,我们现在就可以为其定义算数运算了...
use std::fmt;#[derive(Debug)]enum List {None,Node(i32, Box<List>),}impl fmt::Display for List {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {match self {List::None => write!(f, "Nil"),List::Node(value, next) => {write!(f, "{}->", value)?;write!(f, "...
0 } } impl fmt::Display for Wrapper { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}]", self.0.join(", ")) } } fn main() { let mut w = Wrapper(vec![String::from("hello"), String::from("world")]); let v = w.wrapper_inner(); v.push...
]enumUpstreamError{IO(std::io::Error),Parse(std::net::AddrParseError),}//实现displayimplstd:...
struct Rectangle {width: f32,height: f32,}impl Rectangle {// 构造函数fn new(width: f32, height: f32) -> Rectangle {Rectangle { width, height }}// 计算矩形的面积fn area(&self) -> f32 {self.width * self.height}// 计算矩形的周长fn perimeter(&self) -> f32 {(self.width + self...
输出得虽然有点复杂,但容易理解。如果我们就想输出"8C"这样的字符串,则需要实现Display这个trait里的fmt()函数。注意write!语句后面千万别习惯性地加个分号,否则出现的编译错误让人好困惑! usestd::fmt::{Display, Error, Formatter};implDisplayforSuit{// 只用一个字母表示: S,H,D,Cfnfmt(&self, f: &mut...
// 实现Display trait impl fmt::Display for MyCustomError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.desc) } } fn process() -> Result { Err(MyCustomError { desc: "something is wrong".to_string(), ...
impl Display for Book{ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { println!("Id:{},Name:{},Author:{}",self.id,self.name,self.author); let r=Result::Ok(()); return r; } } show2(book);//输出 Id:1,Name:Go语言极简一本通,Author:欢喜...
自定义错误的类型是enum, 和其他语言相比,这有点奇怪。 代码如下: // 定义自定义错误类型#[derive(Debug)]pubenumMyError{FileOpenError(String),ParseError(String),Common(String), }// 实现Error特质implErrorforMyError{}// 实现Display特质以便打印错误信息implfmt::DisplayforMyError{fnfmt(&self, f: &mut...