5 ms·
But shouldn't they (String and slice) have some common super type to make this all easy to use?
by hrjet 12y ago
But shouldn't they (String and slice) have some common super type to make this all easy to use?
- wycats 12y agoYes. It's a design bug that String and slice don't share a common trait and that `.as_slice()` is common simply to use slice methods. I expect that to be fixed before 1.0.
- bjz_ 12y agoAt least you can now do: foo[].some_slice_method()
- kibwen 12y agoI think this is an anti-pattern. I'm not a fan of the slicing syntax in general, which seems to exist only to paper over the missing traits that wycats mentions.
- dbaupp 12y agoWe will almost certainly just have `Deref<str> for String` and so autoderef will handle `some_string.some_slice_method()` correctly.
- kibwen 12y agoWill we be able to kill the slicing syntax, then? :)
- heinrich5991 12y agoSlicing syntax is about being able to do stuff like string[1:3] AFAIK, so I hope it won't get killed.
- wycats 12y agoAlso, the location of storage is slightly more visible (in general) in Rust than in other languages. I have personally found this to be pretty clarifying, because as much a we may like to abstract over it, the location of storage often worms its way into the programming model even in HLLs.
- bjz_ 12y agoIndeed. I feel like learning Rust has helped me grok C and Java much more, because the different forms of allocation is much are visible.
- kibwen 12y agoI don't think a common ancestor is how you want to do this. Instead, I'd encapsulate the common behavior in a trait (a.k.a. an interface, in other languages), and then write functions that accept any parameters that implement that trait. In Rust, you can do this even on "built-in" types like strings. For an example, see the `print_me` function below, which operates on both string types using a trait that I've defined myself. trait WhatIsThis { fn what_is_this(self); } impl WhatIsThis for String { fn what_is_this(self) { println!("'{:s}' is a string!", self); } } impl WhatIsThis for &'static str { fn what_is_this(self) { println!("'{:s}' is a string slice!", self); } } fn print_me<T>(me: T) where T: WhatIsThis { me.what_is_this(); } fn main() { print_me("Blah blah blah"); print_me("Yada yada yada".to_string()); }
- wycats 12y agoAnd I expect virtually all of the methods on slice to be available on String before long. I think it's a bug that this isn't the case today. It's already possible to have a function take "either a String or slice" generically: def print_me<T>(me: T) where T: Str { println!("I am '{:s}'", me.as_slice()); } The overall ergonomics of this (or at least, the well-documented idioms) will certainly improve in the coming months.
- steveklabnik 12y agohttp://doc.rust-lang.org/std/str/trait.Str.html http://doc.rust-lang.org/std/str/trait.Str.html ?