Rust和golang之字符串
Rust赋值在《Rust程序设计语言》中变量与数据的交互的方式(一):移动使用了如下实例, fn main() {
println!("Hello,world!");
let s1 = String::from("hello");
let s2 = s1;
println!("{}",s2);
// println!("{}",s1);
// let s3 = s2.clone();
// println!("{}{}",s3,s2);
}
强调了Rust语言的特异点 error[E0382]: use of moved value: `s1`
--> src/main.rs:6:19
|
4 | let s2 = s1;
| -- value moved here
5 | println!("{}",s2);
6 | println!("{}",s1);
| ^^ value used here after move
|
= note: move occurs because `s1` has type `std::string::String`,which does not implement the `Copy` trait
这个操作被称为“移动”,而不是浅拷贝。 而对于整型这样的在编译时已知大小的类型被整个存储在栈上,所以旧的整型变量在重新赋值后依然可用。 取子串let s = String::from("kingeasternsun");
let firstname = &s[0..4];
let secondname = &s[4..];
println!("{}",firstname);
println!("{}",secondname);
使用..进行取子串的操作,需要注意的是由于String的移动特性,所以要在s前加&. 注意前面的警告,原因时我在代码里定义了一个Rectangle的结构体没有使用,Rust中如果定义了一个结构体但是没有使用会报警告,结构体后续会详细介绍。 golang赋值在golang中,string是一连串不可更改的byte的集合。对于文本字符串在golang中是把文本Unicode code points(runes)转为UTF-8编码格式的byte列表。 s := "hello,kingeastern"
fmt.Println(s[0]) //打印104 对应字符'h'的byte的数值
s[0] = '3'
取子串s := "http://blog.csdn.net/wdy_yx"
fmt.Println(s[0]) //打印104 对应字符'h'的byte的数值
// s[0] = '3'
fmt.Println(s[:4])
fmt.Println(s[7:])
拼接直接使用”+”就可以实现字符串的拼接 s := "http://blog.csdn.net/wdy_yx"
fmt.Println(s[0]) //打印104 对应字符'h'的byte的数值
// s[0] = '3'
fmt.Println(s[:4])
fmt.Println(s[7:])
fmt.Println("this is my websit:" + s)
前面讲过golang里面string类型里面的内容是不可变的,那为什么还可以执行拼接操作呢? s := "http://blog.csdn.net/wdy_yx"
t := s
s += "this is my websit:"
fmt.Println(t)
fmt.Println(s)
代码如下: var buffer bytes.Buffer //Buffer是一个实现了读写方法的可变大小的字节缓冲
for {
//获取要增加的字符
buffer.WriteString(piece)
}
在golang的string中,可以插入任意的byte通过十六进制或8进制方式。 |