我想知道是否可以根据函数中的条件返回不同的类型:如果删除'||,此代码将起作用 bool'和'if/else'语句.
提前致谢.
fn main() {
let vector: Vec<i32> = vec![0, 2, 5, 8, 9];
let targetL i32 = 3;
let found_item = linear_search(vector, target);
println!("{}", &found_item);
}
fn linear_search(vector: Vec<i32>, target: i32) -> i32 || bool {
let mut found: i32 = 0;
for item in vector {
if item == target {
found = item;
break
}
}
if found == 0 {
false
} else {
found
}
}
Run Code Online (Sandbox Code Playgroud) 下面的代码工作正常,但是我要重复很多次,我认为这不是真的。例如,我正在实现两个特征Square,这感觉不对!coordinate()在特征和实现中也重复该功能。
有没有一种方法可以实现此代码而又不会经常重复自己?是否可以实现以下两个特征:
impl BasicInfo && Sides for Square {
....
}
Run Code Online (Sandbox Code Playgroud)
上面的代码不起作用,这只是一个想法。当一个函数可以应用于多个结构时,是否可以在特征中只定义一次BasicInfo并访问它。
fn main() {
let x_1: f64 = 2.5;
let y_1: f64 = 5.2;
let radius_1: f64 = 5.5;
let width_01 = 10.54;
let circle_01 = Circle { x: x_1, y: y_1, radius: radius_1 };
let square_01 = Square { x: x_1, y: y_1, width: width_01, sides: 4 };
println!("circle_01 has an area of {:.3}.",
circle_01.area().round());
println!("{:?}", circle_01);
println!("The coordinate of circle_01 is …Run Code Online (Sandbox Code Playgroud) 我正在尝试在Rust中实现冒泡排序算法,但我遇到了类型不匹配错误.有人可以帮助实施吗?
这也是以我在Python中实现它的方式实现的.我确信有一种质朴的方式来实现这一点.
fn main() {
let mut list = [15, 3, 2, 1, 6, 0];
bubble_sort(list);
println!("order list is: {:?}", &list);
}
fn bubble_sort(list: &mut [usize]) {
for i in 0..&list.len() {
for j in 0..(&list.len()-1) {
if &list[&j] > &list[&j+1] {
&list.swap( &list[&j], &list[&j+1] );
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
Compiling bubble_sort v0.1.0 (file:///home/ranj/Desktop/Rust/algorithms/sorting/bubble_sort)
src/main.rs:5:17: 5:21 error: mismatched types:
expected `&mut [usize]`,
found `[_; 6]`
(expected &-ptr,
found array of 6 elements) [E0308]
src/main.rs:5 bubble_sort(list);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~
src/main.rs:5:17: 5:21 help: …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用selection_sort创建一个排序向量,同时保持原始未排序的向量:
fn main() {
let vector_1: Vec<i32> = vec![15, 23, 4, 2, 78, 0];
let sorted_vector = selection_sort(&vector_1);
println!("{:?} is unsorted, \n{:?} is sorted.", &vector_1, &sorted_vector);
}
fn selection_sort(vector_1: &Vec<i32>) -> Vec<i32> {
let mut vector = vector_1;
let start = 0;
while start != vector.len() {
for index in (start .. vector.len()) {
match vector[index] < vector[start] {
true => vector.swap(index, start),
false => println!("false"), // do nothing
}
}
start += 1;
}
vector
}
Run Code Online (Sandbox Code Playgroud)
错误: …
我正在玩Rust,我想知道如何打印数组和矢量.
let a_vector = vec![1, 2, 3, 4, 5];
let an_array = ["a", "b", "c", "d", "e"];
Run Code Online (Sandbox Code Playgroud)
我想在屏幕上打印,结果应该是这样的:
[1, 2, 3, 4, 5]
["a", "b", "c", "d", "e"]
Run Code Online (Sandbox Code Playgroud)
在python中它是:
lst = ["a", "b", "c", "d", "e"]
print lst
Run Code Online (Sandbox Code Playgroud)
并打印它会显示:
["a", "b", "c", "d", "e"]
Run Code Online (Sandbox Code Playgroud)