Borrow』を利用した引数の汎用化手法について。

概要

Borrow トレイトをうまく使うと、所有と借用を一つの引数でまとめる事ができる。

これが可能なのは Borrow が以下のブランケット実装を持つためである。

サンプル

以下では、func の引数を所有と借用の両方で渡せるようになっている。


use std::{borrow::Borrow, fmt::Display};

fn main() {
    assert_eq!(func::<i32>(1), "1");
    assert_eq!(func::<i32>(&1), "1");
}

fn func<T: Display>(arg: impl Borrow<T>) -> String {
    format!("{}", arg.borrow()).to_string()
}