]> git.lizzy.rs Git - rust.git/commitdiff
TRPL: associated constants
authorSteve Klabnik <steve@steveklabnik.com>
Thu, 30 Apr 2015 17:10:16 +0000 (13:10 -0400)
committerSteve Klabnik <steve@steveklabnik.com>
Sat, 2 May 2015 15:58:30 +0000 (11:58 -0400)
src/doc/trpl/SUMMARY.md
src/doc/trpl/associated-constants.md [new file with mode: 0644]

index 695dc42cb6418a7d9694fe07f48235009bcf8c5d..4dc77aaec5b50aa333350e5fb6b3b1d35a8e1a3f 100644 (file)
@@ -64,5 +64,6 @@
     * [Benchmark Tests](benchmark-tests.md)
     * [Box Syntax and Patterns](box-syntax-and-patterns.md)
     * [Slice Patterns](slice-patterns.md)
+    * [Associated Constants](associated-constants.md)
 * [Glossary](glossary.md)
 * [Academic Research](academic-research.md)
diff --git a/src/doc/trpl/associated-constants.md b/src/doc/trpl/associated-constants.md
new file mode 100644 (file)
index 0000000..1c097be
--- /dev/null
@@ -0,0 +1,79 @@
+% Associated Constants
+
+With the `associated_consts` feature, you can define constants like this:
+
+```rust
+#![feature(associated_consts)]
+
+trait Foo {
+    const ID: i32;
+}
+
+impl Foo for i32 {
+    const ID: i32 = 1;
+}
+
+fn main() {
+    assert_eq!(1, i32::ID);
+}
+```
+
+Any implementor of `Foo` will have to define `ID`. Without the definition:
+
+```rust,ignore
+#![feature(associated_consts)]
+
+trait Foo {
+    const ID: i32;
+}
+
+impl Foo for i32 {
+}
+```
+
+gives
+
+```text
+error: not all trait items implemented, missing: `ID` [E0046]
+     impl Foo for i32 {
+     }
+```
+
+A default value can be implemented as well:
+
+```rust
+#![feature(associated_consts)]
+
+trait Foo {
+    const ID: i32 = 1;
+}
+
+impl Foo for i32 {
+}
+
+impl Foo for i64 {
+    const ID: i32 = 5;
+}
+
+fn main() {
+    assert_eq!(1, i32::ID);
+    assert_eq!(5, i64::ID);
+}
+```
+
+As you can see, when implementing `Foo`, you can leave it unimplemented, as
+with `i32`. It will then use the default value. But, as in `i64`, we can also
+add our own definition.
+
+Associated constants don’t have to be associated with a trait. An `impl` block
+for a `struct` works fine too:
+
+```rust
+#![feature(associated_consts)]
+
+struct Foo;
+
+impl Foo {
+    pub const FOO: u32 = 3;
+}
+```