teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

3

誤植の訂正

2019/09/29 13:19

投稿

Yhaya
Yhaya

スコア439

title CHANGED
File without changes
body CHANGED
@@ -52,7 +52,7 @@
52
52
  let ans1 = i as i32;
53
53
  let ans2 = j as i32;
54
54
 
55
- return vec![num1, num2];
55
+ return vec![ans1, ans2];
56
56
  ```
57
57
  をif文の中に入れたところ次のようなエラーが出ました。
58
58
 

2

試したことを追記

2019/09/29 13:18

投稿

Yhaya
Yhaya

スコア439

title CHANGED
File without changes
body CHANGED
@@ -44,4 +44,36 @@
44
44
  error: aborting due to 2 previous errors
45
45
 
46
46
  For more information about this error, try `rustc --explain E0308`.
47
+ ```
48
+
49
+ 試したこと: as で usize -> i32 へ変換する
50
+
51
+ ```rust
52
+ let ans1 = i as i32;
53
+ let ans2 = j as i32;
54
+
55
+ return vec![num1, num2];
56
+ ```
57
+ をif文の中に入れたところ次のようなエラーが出ました。
58
+
59
+ ```bash
60
+ error[E0308]: mismatched types
61
+ --> src/main.rs:2:5
62
+ |
63
+ 1 | fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
64
+ | -------- expected `std::vec::Vec<i32>` because of return type
65
+ 2 | / for i in 0..(nums.len() - 1) {
66
+ 3 | | for j in i..nums.len() {
67
+ 4 | | if nums[i] + nums[j] == target {
68
+ 5 | | let ans1 = i as i32;
69
+ ... |
70
+ 10 | |
71
+ 11 | | }
72
+ | |_____^ expected struct `std::vec::Vec`, found ()
73
+ |
74
+ = note: expected type `std::vec::Vec<i32>`
75
+ found type `()`
76
+
77
+ error: aborting due to previous error
78
+ For more information about this error, try `rustc --explain E0308`.
47
79
  ```

1

エラーメッセージの追記

2019/09/29 13:18

投稿

Yhaya
Yhaya

スコア439

title CHANGED
File without changes
body CHANGED
@@ -14,4 +14,34 @@
14
14
  ```
15
15
  しかし、i, jはusize型なので返り値の型がエラーになります。これはネット上の問題として解いているので返り値の型は出題側に決められていて変えることができません。なので何とかしてusize -> i32 にキャストしたいのですが方法がわかりません。
16
16
 
17
- Rust 自体が初心者なのでこの考え方自体があっているかどうかも知りたいです。よろしくお願いします。
17
+ Rust 自体が初心者なのでこの考え方自体があっているかどうかも知りたいです。よろしくお願いします。
18
+
19
+ (追記) エラーメッセージ
20
+ ```bash
21
+ error[E0308]: mismatched types
22
+ --> src/main.rs:5:29
23
+ |
24
+ 5 | return vec![i, j];
25
+ | ^ expected i32, found usize
26
+
27
+ error[E0308]: mismatched types
28
+ --> src/main.rs:2:5
29
+ |
30
+ 1 | fn my_func(nums: Vec<i32>, target: i32) -> Vec<i32> {
31
+ | -------- expected `std::vec::Vec<i32>` because of return type
32
+ 2 | / for i in 0..(nums.len() - 1) {
33
+ 3 | | for j in i..nums.len() {
34
+ 4 | | if nums[i] + nums[j] == target {
35
+ 5 | | return vec![i, j];
36
+ ... |
37
+ 8 | |
38
+ 9 | | }
39
+ | |_____^ expected struct `std::vec::Vec`, found ()
40
+ |
41
+ = note: expected type `std::vec::Vec<i32>`
42
+ found type `()`
43
+
44
+ error: aborting due to 2 previous errors
45
+
46
+ For more information about this error, try `rustc --explain E0308`.
47
+ ```