Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

字符串切片

#![allow(unused)]
fn main() {
let x = String::from("hello");

let y = &x[..2] // output: he  
let z = &x[..=2] // output: hel 包含x[2]
}
  • &x[..2] 这里是对字符串x的引用,必须要加&符号,否则会报错
  • 如果是获得所有权 则不能用切片