質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Rust

Rustは、MoFoが支援するプログラミング言語。高速性を維持しつつも、メモリ管理を安全に行うことが可能な言語です。同じコンパイル言語であるC言語やC++では困難だったマルチスレッドを実装しやすく、並行性という点においても優れています。

Q&A

解決済

1回答

4620閲覧

lib.rsに定義されたtraitをmain.rsで使用する(The Rust Programming Language 10.2)

ataoka

総合スコア13

Rust

Rustは、MoFoが支援するプログラミング言語。高速性を維持しつつも、メモリ管理を安全に行うことが可能な言語です。同じコンパイル言語であるC言語やC++では困難だったマルチスレッドを実装しやすく、並行性という点においても優れています。

0グッド

0クリップ

投稿2021/04/04 01:32

前提・実現したいこと

The Rust Programming Language (日本語版)で学習中です。
chapter10.2で「use chapter10::{self, Summary, Tweet};」というコードがありますが、"chapter10"というディレクトリやファイルをどう作成すればよいかが不明なため、定義したtraitを読み込めずエラーとなります。

lib.rsに記載のtraitをmain.rsで呼び出すにはどうすればよいのでしょうか。

発生している問題・エラーメッセージ

error[E0432]: unresolved import `chapter10` --> main.rs:1:17 | 1 | use chapter10::{self, Summary, Tweet}; | ^^^^ no `chapter10` in the root error[E0422]: cannot find struct, variant or union type `Tweet` in this scope --> main.rs:4:17 | 4 | let tweet = Tweet{ | ^^^^^ not found in this scope error: aborting due to 2 previous errors Some errors have detailed explanations: E0422, E0432. For more information about an error, try `rustc --explain E0422`.

ディレクトリ構成

以下の2つで試しましたがいずれも同じエラーとなりました。

ケース1

chapter10/src/main.rs
chapter10/src/lib.rs

ケース2

chapter10/src/main.rs
chapter10/src/chapter10/lib.rs

該当のソースコード

いずれも、The Rust Programming Languageのコピーです。

lib.rs

Rust

1#![allow(unused)] 2fn main() { 3 pub trait Summary { 4 fn summarize(&self) -> String; 5 } 6 7 8 pub struct NewsArticle{ 9 pub headline: String, 10 pub location: String, 11 pub author: String, 12 pub content: String, 13 } 14 15 impl Summary for NewsArticle{ 16 fn summarize(&self) -> String{ 17 format!{"{}, by {} ({})", self.headline, self.author, self.location} 18 } 19 } 20 21 pub struct Tweet { 22 pub username: String, 23 pub content: String, 24 pub reply: bool, 25 pub retweet: bool, 26 } 27 28 impl Summary for Tweet{ 29 fn summarize(&self) -> String{ 30 format!("{}: {}", self.username, serlf.content) 31 } 32 } 33}

main.rs

Rust

1use chapter10::{self, Summary, Tweet}; 2 3fn main() { 4 let tweet = Tweet { 5 username: String::from("horse_ebooks"), 6 content: String::from( 7 // もちろん、ご存知かもしれませんがね、みなさん 8 "of course, as you probably already know, people", 9 ), 10 reply: false, 11 retweet: false, 12 }; 13 14 println!("1 new tweet: {}", tweet.summarize()); 15}

補足情報(FW/ツールのバージョンなど)

cargo 1.50.0 (f04e7fab7 2021-02-04)
rustc 1.50.0 (cb75ad5db 2021-02-10)

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

クレート(パッケージ)のsrcディレクトリー内にlib.rsmain.rsがある場合、自分自身(自クレート)には以下のようにしてアクセスします。

  • lib.rsからアクセスする場合:use crate;
  • main.rsからアクセスする場合:use クレート名;

ここで、クレート名は、Cargo.tomlの[package]nameで指定したものを使用します。

toml

1[package] 2name = "chapter10" # この名前を使う。(ただし"-"があったら、useでは"_"で置き換える)

ですから、ディレクトリー構成は「ケース1」で、Cargo.tomlの[package]name"chapter10"になっているか確認してください。(ディレクトリー名はchapter10でなくても大丈夫です)

また、lib.rsfn main()がありますが、削除して以下のようにしてください。

rust

1pub trait Summary { 2 fn summarize(&self) -> String; 3} 4 5pub struct NewsArticle{ 6 pub headline: String, 7 pub location: String, 8 pub author: String, 9 pub content: String, 10} 11 12impl Summary for NewsArticle{ 13 fn summarize(&self) -> String{ 14 format!{"{}, by {} ({})", self.headline, self.author, self.location} 15 } 16} 17 18pub struct Tweet { 19 pub username: String, 20 pub content: String, 21 pub reply: bool, 22 pub retweet: bool, 23} 24 25impl Summary for Tweet{ 26 fn summarize(&self) -> String{ 27 format!("{}: {}", self.username, serlf.content) 28 } 29}

追記

回答いただいた内容に納得でき、修正したのですが同じエラーが発生してしまいます。
他に原因が思い当たる場所はございますでしょうか?

うーん。おかしいですですね。なぜでしょう。

もしかしてcargo runではなくて、rustcを直接実行してますか? その場合は確かにエラーになるはずです。

console

1$ rustc src/main.rs 2error[E0432]: unresolved import `chapter10` 3 --> src/main.rs:1:17 4 | 51 | use chapter10::{self, Summary, Tweet}; 6 | ^^^^ no `chapter10` in the root 7 8error[E0422]: cannot find struct, variant or union type `Tweet` in this scope 9 --> src/main.rs:4:17 10 | 114 | let tweet = Tweet { 12 | ^^^^^ not found in this scope 13 14error: aborting due to 2 previous errors 15 16Some errors have detailed explanations: E0422, E0432. 17For more information about an error, try `rustc --explain E0422`.

もしそうでしたらcargo runで実行してください。

console

1$ cargo run 2 Finished dev [unoptimized + debuginfo] target(s) in 0.46s 3 Running `target/debug/chapter10` 41 new tweet: horse_ebooks: of course, as you probably already know, people

私の方でも質問者さまと同じ構成で試しています。以下の内容で動きました。

console

1## 私は中国に住んでいるので、日本との時差が1時間あります。 2##(中国 19:53 → 日本 20:53) 3 4$ exa -lT ../trait_test 5drwxr-xr-x - tatsuya 6 Apr 19:53 ../trait_test 6.rw-r--r-- 93 tatsuya 6 Apr 19:48 ├── Cargo.toml 7drwxr-xr-x - tatsuya 6 Apr 19:48 └── src 8.rw-r--r-- 582 tatsuya 6 Apr 19:48 ├── lib.rs 9.rw-r--r-- 419 tatsuya 6 Apr 19:48 └── main.rs 10 11$ cat Cargo.toml 12[package] 13name = "chapter10" 14version = "0.1.0" 15authors = [] 16edition = "2018" 17 18[dependencies] 19 20$ cat src/main.rs 21use chapter10::{self, Summary, Tweet}; 22 23fn main() { 24 let tweet = Tweet { 25 username: String::from("horse_ebooks"), 26 content: String::from( 27 // もちろん、ご存知かもしれませんがね、みなさん 28 "of course, as you probably already know, people", 29 ), 30 reply: false, 31 retweet: false, 32 }; 33 34 println!("1 new tweet: {}", tweet.summarize()); 35} 36 37$ cat src/lib.rs 38pub trait Summary { 39 fn summarize(&self) -> String; 40} 41 42pub struct NewsArticle { 43 pub headline: String, 44 pub location: String, 45 pub author: String, 46 pub content: String, 47} 48 49impl Summary for NewsArticle { 50 fn summarize(&self) -> String { 51 format! {"{}, by {} ({})", self.headline, self.author, self.location} 52 } 53} 54 55pub struct Tweet { 56 pub username: String, 57 pub content: String, 58 pub reply: bool, 59 pub retweet: bool, 60} 61 62impl Summary for Tweet { 63 fn summarize(&self) -> String { 64 format!("{}: {}", self.username, self.content) 65 } 66} 67 68$ rustc -V 69rustc 1.51.0 (2fd73fabe 2021-03-23) 70 71$ cargo run 72 Compiling chapter10 v0.1.0 (... /trait_test) 73 Finished dev [unoptimized + debuginfo] target(s) in 1.15s 74 Running `target/debug/chapter10` 751 new tweet: horse_ebooks: of course, as you probably already know, people

投稿2021/04/04 01:51

編集2021/04/06 12:52
tatsuya6502

総合スコア2035

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ataoka

2021/04/06 11:40

ご回答頂きありがとうございます。 回答いただいた内容に納得でき、修正したのですが同じエラーが発生してしまいます。 他に原因が思い当たる場所はございますでしょうか? 各ディレクトリの構成は以下になっています。 trait_test/src/main.rs trait_test/src/lib.rs trait_test/Cargo.toml Cargo.toml ```Rust [package] name = "chapter10" //念の為、nameとmain.rsのuseを"trait_test"で実施してみましたが、結果は同じでした。 version = "0.1.0" authors = ["****"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] ``` main.rs ```Rust use chapter10::{self, Summary, Tweet}; 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, }; println!("1 new tweet: {}", tweet.summarize()); } ``` lib.rs(fn.mainを削除した以外は同じ。) ```Rust pub trait Summary { fn summarize(&self) -> String; } 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} } } 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) } } ```
tatsuya6502

2021/04/06 12:09

状況について承知しました。回答の方に追記しました。
ataoka

2021/04/11 01:06

ありがとうございます、cargo runで実行すると問題なく実行できました。 詳細にご確認頂きありがとうございました。助かりました。
tatsuya6502

2021/04/11 01:54

解決してよかったです!
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問