Skip to content

「6. 型変換」などを翻訳 #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Nov 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@
- [Declare first](variable_bindings/declare.md)
- [Freezing](variable_bindings/freeze.md)
-->
- [変数バインディング](variable_bindings.md)
- [変数束縛](variable_bindings.md)
- [ミュータビリティ](variable_bindings/mut.md)
- [スコープとシャドーイング](variable_bindings/scope.md)
- [宣言](variable_bindings/declare.md)
- [値のフリーズ](variable_bindings/freeze.md)
- [値の凍結](variable_bindings/freeze.md)

<!--
- [Types](types.md)
Expand All @@ -67,16 +67,22 @@
- [Inference](types/inference.md)
- [Aliasing](types/alias.md)
-->
- [Types](types.md)
- [](types.md)
- [型キャスティング](types/cast.md)
- [リテラル](types/literals.md)
- [型推論](types/inference.md)
- [エイリアス](types/alias.md)

<!--
- [Conversion](conversion.md)
- [`From` and `Into`](conversion/from_into.md)
- [`TryFrom` and `TryInto`](conversion/try_from_try_into.md)
- [To and from `String`s](conversion/string.md)
-->
- [型変換](conversion.md)
- [`From`および`Into`](conversion/from_into.md)
- [`TryFrom`および`TryInto`](conversion/try_from_try_into.md)
- [`String`との型変換](conversion/string.md)

<!--
- [Expressions](expression.md)
Expand Down Expand Up @@ -106,7 +112,7 @@
- [if/else](flow_control/if_else.md)
- [loop](flow_control/loop.md)
- [ネストとラベル](flow_control/loop/nested.md)
- [Returning from loops](flow_control/loop/return.md)
- [loopが返す値](flow_control/loop/return.md)
- [while](flow_control/while.md)
- [for と range](flow_control/for.md)
- [match](flow_control/match.md)
Expand Down
6 changes: 6 additions & 0 deletions src/conversion.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
<!--
# Conversion
-->
# 型変換

<!--
Rust addresses conversion between types by the use of [traits]. The generic
conversions will use the [`From`] and [`Into`] traits. However there are more
specific ones for the more common cases, in particular when converting to and
from `String`s.
-->
Rustは型の変換を[トレイト][traits]を用いて行います。ジェネリックな型変換には[`From`]および[`Into`]トレイトを使用します。しかし、よくあるケースにおいて、特に`String`との相互の型変換では、特殊なトレイトが使用されます。

[traits]: trait.md
[`From`]: https://doc.rust-lang.org/std/convert/trait.From.html
Expand Down
21 changes: 21 additions & 0 deletions src/conversion/from_into.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,39 @@
<!--
# `From` and `Into`
-->
# `From`および`Into`

<!--
The [`From`] and [`Into`] traits are inherently linked, and this is actually part of
its implementation. If you are able to convert type A from type B, then it
should be easy to believe that we should be able to convert type B to type A.
-->
[`From`]トレイトと[`Into`]トレイトは本質的に結びついており、そのことが実際に実装に反映されています。もし型Aから型Bへの変換ができるのであれば、型Bから型Aへの変換もできると思うのが自然です。

## `From`

<!--
The [`From`] trait allows for a type to define how to create itself from another
type, hence providing a very simple mechanism for converting between several
types. There are numerous implementations of this trait within the standard
library for conversion of primitive and common types.
-->
[`From`]トレイトは、ある型に対し、別の型からその型を作る方法を定義できるようにするものです。そのため、複数の型の間で型変換を行うための非常にシンプルな仕組みを提供しています。標準ライブラリでは、基本データ型やよく使われる型に対して、このトレイトが多数実装されています。
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

自己レビューですが、「そのため、複数の型の間で〜」は「これにより、複数の型の間で〜」の方が、自然な言い回しだったかもしれません。


<!--
For example we can easily convert a `str` into a `String`
-->
例えば、`str`から`String`への型変換は簡単です。

```rust
let my_str = "hello";
let my_string = String::from(my_str);
```

<!--
We can do similar for defining a conversion for our own type.
-->
自作の型に対しても、型変換を定義すれば同じように行えます。

```rust,editable
use std::convert::From;
Expand All @@ -42,13 +57,19 @@ fn main() {

## `Into`

<!--
The [`Into`] trait is simply the reciprocal of the `From` trait. That is, if you
have implemented the `From` trait for your type, `Into` will call it when
necessary.
-->
[`Into`]トレイトは、単に`From`トレイトの逆の働きをします。もし自作の型に`From`トレイトが実装されていたら、`Into`は必要に応じてそれを呼び出します。

<!--
Using the `Into` trait will typically require specification of the type to
convert into as the compiler is unable to determine this most of the time.
However this is a small trade-off considering we get the functionality for free.
-->
`Into`トレイトを使用すると、ほとんどの場合、コンパイラが型を決定することができないため、変換する型を指定する必要があります。しかし、この機能を無料で得られることを考えれば、これは小さなトレードオフです。

```rust,editable
use std::convert::From;
Expand Down
18 changes: 18 additions & 0 deletions src/conversion/string.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
<!--
# To and from Strings
-->
# Stringとの型変換

<!--
## Converting to String
-->
## Stringへの型変換

<!--
To convert any type to a `String` is as simple as implementing the [`ToString`]
trait for the type. Rather than doing so directly, you should implement the
[`fmt::Display`][Display] trait which automagically provides [`ToString`] and
also allows printing the type as discussed in the section on [`print!`][print].
-->
任意の型を`String`に変換するのは簡単で、その型に[`ToString`]トレイトを実装するだけです。これを直接実装するよりも、[`fmt::Display`][Display]トレイトを実装するのがよいでしょう。そうすることで自動的に[`ToString`]が提供されるだけでなく、[`print!`][print]の章で説明したように、その型を表示できるようにもなります。

```rust,editable
use std::fmt;
Expand All @@ -26,17 +35,26 @@ fn main() {
}
```

<!--
## Parsing a String
-->
## Stringの解析

<!--
One of the more common types to convert a string into is a number. The idiomatic
approach to this is to use the [`parse`] function and either to arrange for
type inference or to specify the type to parse using the 'turbofish' syntax.
Both alternatives are shown in the following example.
-->
文字列からの型変換において、数値への型変換はよく行われるものの一つです。これを行うイディオムは[`parse`]関数を使用することですが、このときに型を推論できるようにするか、もしくは turbofish構文を使用して型を指定するかのいずれかを行います。以下の例では、どちらの方法も紹介しています。

<!--
This will convert the string into the type specified so long as the [`FromStr`]
trait is implemented for that type. This is implemented for numerous types
within the standard library. To obtain this functionality on a user defined type
simply implement the [`FromStr`] trait for that type.
-->
`parse`関数は、指定された型に`FromStr`トレイトが実装されていれば、文字列をその型に変換します。このトレイトは標準ライブラリの多くの型に対して実装されています。ユーザー定義の型でこの機能を利用するには、その型に対して`FromStr`トレイトを実装するだけです。

```rust,editable
fn main() {
Expand Down
7 changes: 7 additions & 0 deletions src/conversion/try_from_try_into.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
<!--
# `TryFrom` and `TryInto`
-->
# `TryFrom`および`TryInto`

<!--
Similar to [`From` and `Into`][from-into], [`TryFrom`] and [`TryInto`] are
generic traits for converting between types. Unlike `From`/`Into`, the
`TryFrom`/`TryInto` traits are used for fallible conversions, and as such,
return [`Result`]s.
-->
[`From`および`Into`][from-into]と同様に、[`TryFrom`]および[`TryInto`]も型変換を行うジェネリックなトレイトです。`From`/`Into`と異なり、`TryFrom`/`TryInto`トレイトは失敗する可能性のある型変換に用いられるので、[`Result`]を返します。


[from-into]: from_into.html
[`TryFrom`]: https://doc.rust-lang.org/std/convert/trait.TryFrom.html
Expand Down
26 changes: 25 additions & 1 deletion src/custom_types/enum.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,26 +8,35 @@ The `enum` keyword allows the creation of a type which may be one of a few
different variants. Any variant which is valid as a `struct` is also valid as
an `enum`.
-->
列挙型(`enum`)はいくつかの異なる型の中から1つを選ぶような場合に使用する。構造体(`struct`)の定義を満たすものならば何でも`enum` 内の型として使用できる
列挙型(`enum`)はいくつかの異なる要素型の中から1つを選ぶような場合に使用します。構造体(`struct`)の定義を満たすものならば何でも`enum` の要素型として使用できます。

```rust,editable
// Create an `enum` to classify a web event. Note how both
// names and type information together specify the variant:
// `PageLoad != PageUnload` and `KeyPress(char) != Paste(String)`.
// Each is different and independent.
// `enum`を作成してwebイベントを分類する。
// 名前と型情報を併せたものが要素型になっていることに注意。
// `PageLoad != PageUnload` であり、
// `KeyPress(char) != Paste(String)` である。
// 要素型は互いに異なり、互いに非依存である。
enum WebEvent {
// An `enum` may either be `unit-like`,
// `enum`要素型はユニット風でもよい
PageLoad,
PageUnload,
// like tuple structs,
// タプル風でもよい
KeyPress(char),
Paste(String),
// or c-like structures.
// C言語スタイルの構造体風でもよい
Click { x: i64, y: i64 },
}

// A function which takes a `WebEvent` enum as an argument and
// returns nothing.
// 引数として`WebEvent`列挙型をとり、何も返さない関数
fn inspect(event: WebEvent) {
match event {
WebEvent::PageLoad => println!("page loaded"),
Expand All @@ -45,6 +54,7 @@ fn inspect(event: WebEvent) {
fn main() {
let pressed = WebEvent::KeyPress('x');
// `to_owned()` creates an owned `String` from a string slice.
// `to_owned()`は文字列スライスから所有権のある`String`を作成する
let pasted = WebEvent::Paste("my text".to_owned());
let click = WebEvent::Click { x: 20, y: 80 };
let load = WebEvent::PageLoad;
Expand All @@ -59,11 +69,17 @@ fn main() {

```

<!--
## Type aliases
-->
## 型エイリアス

<!--
If you use a type alias, you can refer to each enum variant via its alias.
This might be useful if the enum's name is too long or too generic, and you
want to rename it.
-->
型エイリアスを用いると、列挙型の要素型を別名で参照できます。これは列挙型の名前があまりに長かったり、あまりに一般的だったりで改名したい場合に役立ちます。

```rust,editable
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Expand All @@ -72,16 +88,21 @@ enum VeryVerboseEnumOfThingsToDoWithNumbers {
}

// Creates a type alias
// 型エイリアスを作成する
type Operations = VeryVerboseEnumOfThingsToDoWithNumbers;

fn main() {
// We can refer to each variant via its alias, not its long and inconvenient
// name.
// 長くて不便な列挙型の名前ではなく、別名を使って要素型を参照できる
let x = Operations::Add;
}
```

<!--
The most common place you'll see this is in `impl` blocks using the `Self` alias.
-->
このやり方がもっともよく見られるのは、`impl`ブロックで`Self`という別名を使用する場合です。

```rust,editable
enum VeryVerboseEnumOfThingsToDoWithNumbers {
Expand All @@ -99,9 +120,12 @@ impl VeryVerboseEnumOfThingsToDoWithNumbers {
}
```

<!--
To learn more about enums and type aliases, you can read the
[stabilization report][aliasreport] from when this feature was stabilized into
Rust.
-->
列挙型や型エイリアスについて詳しく学びたい人は、この機能が安定してRustに取り込まれた後に[stabilization report][aliasreport]を読んでください。

<!--
### See also:
Expand Down
9 changes: 9 additions & 0 deletions src/custom_types/structs.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,21 +47,25 @@ struct Point {
struct Rectangle {
// A rectangle can be specified by where the top left and bottom right
// corners are in space.
// 長方形は座標空間上における左上隅と右下隅の位置によって指定できる
top_left: Point,
bottom_right: Point,
}

fn main() {
// Create struct with field init shorthand
// 構造体をフィールド初期化の簡略記法で生成
let name = "Peter";
let age = 27;
let peter = Person { name, age };

// Print debug struct
// 構造体のデバッグ表示を行う
println!("{:?}", peter);


// Instantiate a `Point`
// `Point` のインスタンス化
let point: Point = Point { x: 10.3, y: 0.4 };

// Access the fields of the point
Expand All @@ -70,10 +74,14 @@ fn main() {

// Make a new point by using struct update syntax to use the fields of our
// other one
// 構造体の更新記法を用いて、別の構造体のフィールドの値を基に
// 新たなpointを生成
let bottom_right = Point { x: 5.2, ..point };

// `bottom_right.y` will be the same as `point.y` because we used that field
// from `point`
// `bottom_right.y` の値は `point.y` と同一になるが、
// これは `point` のフィールドの値を用いて生成したためである
println!("second point: ({}, {})", bottom_right.x, bottom_right.y);

// Destructure the point using a `let` binding
Expand All @@ -96,6 +104,7 @@ fn main() {
let pair = Pair(1, 0.1);

// Access the fields of a tuple struct
// タプルのフィールドにアクセス
println!("pair contains {:?} and {:?}", pair.0, pair.1);

// Destructure a tuple struct
Expand Down
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy