fn main() {
let mut v = vec![3, 2, 5, 1, 4];
println!("before sort, v = {:?}", v);
bubble_sort(&mut v);
println!("after sort, v = {:?}", v);
}
fn bubble_sort<T>(v: &mut [T])
where
T: PartialOrd + Copy,
{
for i in 1..v.len() {
for j in 0..(v.len() - i) {
if v[j] > v[j + 1] {
v.swap(j, j + 1);
}
}
}
}
fn main() {
let mut v = vec![3, 2, 5, 1, 4];
println!("before sort, v = {:?}", v);
bubble_sort(&mut v);
println!("after sort, v = {:?}", v);
}
fn bubble_sort<T>(v: &mut [T])
where
T: PartialOrd + Copy,
{
let mut i = 0;
while i < v.len() {
let mut j = v.len() - 1;
while j > i {
if v[j - 1] > v[j] {
v.swap(j - 1, j);
}
j -= 1;
}
i += 1;
}
}
fn largest_i32(list: &[i32]) -> i32 {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
fn largest_char(list: &[char]) -> char {
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
/*
只有实现了 PartialOrd 这个 trait 的泛型才能够比较大小。
只有实现了 Copy trait 的泛型才能在使用赋值 = 的时候执行按位拷贝。
*/
fn largest1<T>(list: &[T]) -> T
where
T: PartialOrd + Copy,
{
let mut largest = list[0];
for &item in list.iter() {
if item > largest {
largest = item;
}
}
largest
}
/*
泛型 T 如果不实现 Copy trait,也可以用 Clone trait。
Clone trait 则必须显示调用 clone() 函数。
*/
fn largest2<T>(list: &[T]) -> T
where
T: PartialOrd + Clone,
{
let mut largest = list[0].clone();
let mut i = 0;
while i < list.len() {
if list[i] > largest {
largest = list[i].clone();
}
i += 1;
}
largest
}
/*
也可以修改返回值为对数组中变量的租借,这样的话,根据生命周期自动标注规则,
返回值的生命周期必须和输入的数组一样长。
而 largest1 和 largest2 中的返回值则和输入参数没有任何关系。
*/
fn largest3<T>(list: &[T]) -> &T
where
T: PartialOrd,
{
let mut largest = &list[0];
let mut i = 0;
while i < list.len() {
let item = &list[i];
if item > largest {
largest = item;
}
i += 1;
}
largest
}
fn main() {
println!("Hello, world!");
let number_list = vec![1, 2, 3, 4, 5];
let result = largest_i32(&number_list);
println!("The largest number is {}", result);
let char_list = vec!['R', 'u', 's', 't'];
let result = largest_char(&char_list);
println!("The largest char is {}", result);
println!("largest1, The largest number is {}", largest1(&number_list));
println!("largest1, The largest char is {}", largest1(&char_list));
println!("largest2, The largest number is {}", largest2(&number_list));
println!("largest2, The largest char is {}", largest2(&char_list));
println!("largest3, The largest number is {}", largest3(&number_list));
println!("largest3, The largest char is {}", largest3(&char_list));
}
use std::fmt::Display;
fn longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
where
T: Display,
{
println!("Announcement! {}", ann);
if x.len() > y.len() {
x
} else {
y
}
}
fn main() {
println!("Hello, world!");
}
use std::fmt;
struct Point1<T> {
x: T,
y: T,
}
impl<T> Point1<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
fn x(&self) -> &T {
&self.x
}
}
impl<T: fmt::Display + PartialOrd> Point1<T> {
fn cmp_display(&self) {
if self.x > self.y {
println!("The largest number is x = {}", self.x);
} else {
println!("The largest number is y = {}", self.y);
}
}
}
impl Point1<f32> {
fn distance_from_origin(&self) -> f32 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
#[derive(Debug)]
struct Point2<A, B> {
x: A,
y: B,
}
impl<A, B> Point2<A, B> {
fn mixup<C, D>(self, other: Point2<C, D>) -> Point2<A, D> {
Point2 {
x: self.x,
y: other.y,
}
}
}
fn main() {
println!("Hello, world!");
let integer = Point1 { x: 5, y: 10 };
let float = Point1 { x: 1.0, y: 4.0 };
println!("interger.x = {}", integer.x());
println!("float.x = {}", float.x());
println!(
"float.distance_from_origin = {}",
float.distance_from_origin()
);
// expected integer, found floating-point number
// let wont_work = Point1 { x: 5, y: 4.0 };
let p1 = Point2 { x: 5, y: 4.0 };
let p2 = Point2 {
x: "hello",
y: "world",
};
let p3 = p1.mixup(p2);
println!("p3 = {:?}", p3);
}
use std::fmt;
pub trait Summary {
fn summarize(&self) -> String;
fn new_summarize(&self) -> String {
format!("(Read more from {}...)", self.summarize_author())
}
fn summarize_author(&self) -> String;
}
#[derive(Debug)]
pub struct NewsArticle {
pub headline: String,
pub location: String,
pub author: String,
pub content: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}, by {} {}", self.headline, self.author, self.location)
}
fn summarize_author(&self) -> String {
String::from("")
}
}
impl fmt::Display for NewsArticle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}, by {} {}", self.headline, self.author, self.location)
}
}
pub struct Tweet {
pub username: String,
pub content: String,
pub reply: bool,
pub retweet: bool,
}
impl Summary for Tweet {
fn summarize(&self) -> String {
format!("{}: {}", self.username, self.content)
}
fn summarize_author(&self) -> String {
format!("@{}", self.username)
}
}
impl fmt::Display for Tweet {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}: {}", self.username, self.content)
}
}
impl Tweet {
fn show(&self) {
println!("{}: {}", self.username, self.content)
}
}
/*
notify1, notify2, notify3 实现相同的行为。
*/
pub fn notify1(item: &impl Summary) {
println!("notify1 Breaking news! {}", item.summarize());
}
pub fn notify2<T: Summary>(item: &T) {
println!("notify2 Breaking news! {}", item.summarize());
}
pub fn notify3<T>(item: &T)
where
T: Summary,
{
println!("notify3 Breaking news! {}", item.summarize());
}
/*
notify4, notify5, notify6 实现相同的行为。
*/
pub fn notify4(item: &(impl Summary + fmt::Display)) {
println!("notify4 Breaking news! {}", item);
}
pub fn notify5<T: Summary + fmt::Display>(item: &T) {
println!("notify5 Breaking news! {}", item);
}
pub fn notify6<T>(item: &T)
where
T: Summary + fmt::Display,
{
println!("notify6 Breaking news! {}", item);
}
/*
bignotify1, bignotify2, bignotify3 实现相同的行为。
*/
pub fn bignotify1(
T: &(impl Summary + fmt::Display),
U: &(impl Summary + fmt::Display + fmt::Debug),
) {
println!("bignotify1 Breaking news! \n\t{}\n\t{}", T, U);
}
pub fn bignotify2<T: Summary + fmt::Display, U: Summary + fmt::Display + fmt::Debug>(t: &T, u: &U) {
println!("bignotify2 Breaking news! \n\t{}\n\t{}", t, u);
}
pub fn bignotify3<T, U>(t: &T, u: &U)
where
T: Summary + fmt::Display,
U: Summary + fmt::Display + fmt::Debug,
{
println!("bignotify3 Breaking news! \n\t{}\n\t{}", t, u);
}
fn main() {
let tweet = Tweet {
username: String::from("horse_ebooks"),
content: String::from("of course, as you probably already know, people"),
reply: false,
retweet: false,
};
tweet.show();
println!("1 new tweet: {}", tweet.summarize());
println!("1 new tweet: {}", tweet.new_summarize());
let article = NewsArticle {
headline: String::from("Penguins win the Stanley Cup Championship!"),
location: String::from("Pittsburgh, PA, USA"),
author: String::from("Iceburgh"),
content: String::from(
"The Pittsburgh Penguins once again are the best hockey team in the NHL.",
),
};
println!("New article available! {}", article.summarize());
println!();
notify1(&tweet);
notify1(&article);
notify2(&tweet);
notify2(&article);
notify3(&tweet);
notify3(&article);
println!();
notify4(&tweet);
notify4(&article);
notify5(&tweet);
notify5(&article);
notify6(&tweet);
notify6(&article);
println!();
bignotify1(&tweet, &article);
bignotify2(&tweet, &article);
bignotify3(&tweet, &article);
}
fn test1(mut a: [i32; 3]) {
a[0] = 10;
println!("test1 a = {:?}", a); // test1 a = [10, 2, 3]
}
fn test2(mut b: Vec<i32>) {
b[0] = 20;
println!("test2 b = {:?}", b); // test2 b = [20, 2, 3]
}
fn test3(c: &mut [i32]) {
c[0] = 30;
println!("test3 c = {:?}", c); // test3 c = [30, 2, 3]
}
fn main() {
// a 默认实现 Copy trait,所以在传入 test1 函数时执行了按位拷贝整个数组。
let a = [1, 2, 3];
test1(a);
println!("main a = {:?}", a); // main a = [1, 2, 3]
// b 的所有权转移到了函数 test2 中去了。
let b = vec![1, 2, 3];
test2(b);
// println!("main b = {:?}", b);
// 推荐这么使用,在拥有所有权的地方使用 vector 动态数组,
// 在租借出去的时候,使用 mutable slice 来接收。
let mut c = vec![1, 2, 3];
test3(&mut c);
println!("main c = {:?}", c); // main c = [30, 2, 3]
}
fn main() {
/*
array, a fixed-size list of elements of the type.
By default, arrays are immutable.
[T; N], T is array's element type, and N is the length.
*/
println!("array demo:");
let a = [1, 2, 3]; // a: [i32, 3]
let b: [i32; 3] = [1, 2, 3]; // b: [i32; 3]
assert_eq!(a, b);
/*
create a mutable array c.
*/
let mut c = [1, 2, 3]; // mut c: [i32; 3]
c[0] = 4;
println!("c = {:?}", c);
/*
d.len() = 20, and every element of d will be initialized to 0.
*/
let d = [0; 20]; // d: [i32; 20]
println!("d = {:?}", d);
let e = [1, 2, 3];
println!("e has {} elements", e.len());
for t in e.iter() {
print!("{} ", t);
}
println!();
let names = ["Graydon", "Brian", "Niko"]; // names: [&str; 3]
println!("The second name is: {}", names[1]);
/*
vector, is a dynamic and "growable" array. Vectors always allocate
the data on the heap.
Vec<T>, T is vector's element type.
*/
println!("\nvector demo:");
let v = vec![1, 2, 3]; // v: Vec<i32>
println!("v = {:?}", v);
let mut nums = vec![1, 2, 3]; // mut nums: Vec<i32>
nums.push(4);
println!("The length of nums is now {}", nums.len());
/*
slice, is a reference to an array.
You can also take a slice of a vector, String or &str, because
they are backed by arrays.
&[T], T is slice's element type.
*/
println!("\nslice demo:");
let a = [0, 1, 2, 3, 4];
let middle = &a[1..4]; // middle is a slice of a.
print!("slice of array = ");
for e in middle.iter() {
print!("{} ", e);
}
println!();
let a = vec![0, 1, 2, 3, 4];
let middle = &a[1..4]; // middle is a slice of a.
print!("slice of vector = ");
for e in middle.iter() {
print!("{} ", e);
}
println!();
let a = String::from("01234");
let middle = &a[1..4]; // middle is a slice of a.
println!("slice of String = {}", middle);
let mut a = [0, 1, 2, 3, 4];
let middle = &mut a[1..4]; // middle is a mutable slice of a.
print!("mutable slice of array = ");
for e in middle.iter_mut() {
*e += 10;
print!("{} ", e);
}
println!();
println!("\nothers:");
let x: &mut [i32; 3] = &mut [1, 2, 4]; // &mut [i32; 3] 这个类型应该是对数组 [i32; 3] 的可变引用。
x.len();
x[0] = 10;
println!("x = {:?}", x);
test1();
}
fn test1() {
// a is an array
let mut a = [1, 2, 3];
test(&mut a);
// b is an vector
let mut b = vec![4, 5, 6, 7, 8, 9];
test(&mut b);
// c and d is a slice
let c = &mut a[1..];
let d = &mut c[1..];
test(d);
}
// test function use a mutable slice as parameter.
fn test(a: &mut [i32]) {
for e in a.iter_mut() {
*e += 10
}
println!("slice = {:?}", a);
}
https://www.cs.brandeis.edu/~cs146a/rust/doc-02-21-2015/book/arrays-vectors-and-slices.html
https://rustcc.cn/search?q=Rust%20FFI
rustup component add rust-src 安装当前工具链源码
rustup doc -h 这个是查看当前工具链的文档。
cargo doc -h 这个是查看当前包的文档。
chrome 插件 Rust Search Extension