gpt4 book ai didi

types - 创建一个基本上是 String 但与 String 不兼容的类型?

转载 作者:行者123 更新时间:2023-11-29 07:55:31 26 4
gpt4 key购买 nike

我注意到在我的项目中,我使用了很多 String 类型,我并不是真正的 String 类型,而是 String 中包含的特定类型的值code>String,无法区分,例如通过使用正则表达式,但应该从代码的角度加以区分。有没有办法让编译器帮助我?例如,考虑这个函数:

fn do_something(val1: String, val2: String) {}

fn main() {
let val1: String = "hello";
let val2: String = "hello2";
do_something(val1, val2);
}

有没有一种方法可以创建 SpecificStringType1SpecificStringType2,以便第一个 do_something 调用可以编译,但第二个不能?

fn do_something(val1: SpecificStringType1, val2: SpecificStringType2) {}

fn main() {
let val1: SpecificStringType1 = "hello";
let val2: SpecificStringType2 = "hello2";
let val3: SpecificStringType2 = "hello2";
let val4: SpecificStringType2 = "hello2";
do_something(val1, val2);
do_something(val3, val4);
}

最佳答案

你可以用元组结构包裹 String,创建一个新的不同类型:

// This is a custom type which just wraps String,
// however you can choose what it derives again.
#[derive(Clone, Debug)]
struct MyString(String);

// Since they are distinct types, type check will prevent using
// String as MyString and vice versa.
fn f1(s: &String, t: &String) -> bool {
return true;
}

fn f2(s: &String, t: &MyString) -> bool {
return false;
}

fn main() {
let s: String = "hello".to_string();
let ms = MyString("goodbye".to_string());
let MyString(ms_inner) = ms.clone();

println!("{:?}", &s);
println!("{:?}", &ms);

// Here is proof that it works.
println!("{}", f1(&s, &ms_inner));
println!("{}", f2(&s, &ms));
}

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a32994fab2cabb6495807726f246da1e

关于types - 创建一个基本上是 String 但与 String 不兼容的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com