当我尝试使用以下代码在全局范围中添加const数组时:
static NUMBERS: [i32] = [1, 2, 3, 4, 5];
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
error: mismatched types:
expected `[i32]`,
found `[i32; 5]`
(expected slice,
found array of 5 elements) [E0308]
static NUMBERS2: [i32] = [1, 2, 3, 4, 5];
^~~~~~~~~~~~~~~
Run Code Online (Sandbox Code Playgroud)
我发现处理这个问题的唯一方法是在类型中指定长度:
static NUMBERS: [i32; 5] = [1, 2, 3, 4, 5];
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?应该可以创建一个数组而无需手动计算其元素.
是否可以在使用非预定义参数调用模拟时抛出异常?有Answers.RETURNS_SMART_NULLS,但它并不是我真正需要的东西,因为它不起作用,如果null是合法的返回值,这不会导致NullPointerException,而是后来的错误.
编辑:一些背景.因此,在定义模拟时,在Mockito中,您可以为每个调用指定返回值,如下所示:
when(myMock.someMethod(arg1, arg2)).thenReturn(returnValue);
Run Code Online (Sandbox Code Playgroud)
当myMock.someMethod使用参数调用时,我没有在测试中给出返回值,它只返回null.我想将它配置为立即崩溃并告诉我,我忘了为某些参数组合定义返回值.
编辑2:有人建议提供一个defaultAnswer在调用时抛出异常的自定义.不幸的是,这不起作用.answer()即使存在模拟,也会调用默认答案的方法.这是一个示例:
public class Test {
public static class Adder {
public int add(int a, int b) {
return a + b;
}
}
public static final Answer<Object> THROW_ON_UNDEFINED_ARGS = new Answer<Object>() {
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
throw new IllegalArgumentException(
String.format("Calling a mock with undefined arguments: %s %s",
invocation.getMethod(),
Arrays.toString(invocation.getArguments())));
}
};
public static void main(String[] args) { …Run Code Online (Sandbox Code Playgroud) 假设我期望一个来自stdin的3个整数的行.阅读和解析它们最简单的方法是什么?什么是a, b, c = map(int, input().split())在Python或scanf("%d %d %d", &a, &b, &c);C中的Rust等价物?
我提出的最好方法是:
let mut line = String::new();
io::stdin().read_line(&mut line).unwrap();
let parts: Vec<&str> = line.split_whitespace().collect();
let a: i32 = parts[0].parse().unwrap();
let b: i32 = parts[1].parse().unwrap();
let c: i32 = parts[2].parse().unwrap();
Run Code Online (Sandbox Code Playgroud)
有更简单的方法吗?
我有以下代码尝试从盒装特征中引用特征对象:
trait T {}
struct S {}
impl T for S {}
fn main() {
let struct_box: Box<S> = Box::new(S {});
let struct_ref: &S = &struct_box;
let trait_box: Box<T> = Box::new(S {});
let trait_ref: &T = &trait_box;
}
Run Code Online (Sandbox Code Playgroud)
编译器返回以下错误:
error[E0277]: the trait bound `std::boxed::Box<T>: T` is not satisfied
--> src/main.rs:12:25
|
12 | let trait_ref: &T = &trait_box;
| ^^^^^^^^^^ the trait `T` is not implemented for `std::boxed::Box<T>`
|
= note: required for the cast to the object type `T` …Run Code Online (Sandbox Code Playgroud)