@@ -210,12 +210,15 @@ Hello, World! My name is FrenchToast
210
210
Hello, World! My name is Waffles
211
211
```
212
212
213
+ We've done it!
214
+
213
215
## Custom Attributes
214
216
215
217
In some cases it might make sense to allow users some kind of configuration.
216
- For our example the user might want to overwrite the name that is printed in the ` hello_world() ` method.
218
+ For example, the user might want to overwrite the name that is printed in the ` hello_world() ` method.
217
219
218
220
This can be achieved with custom attributes:
221
+
219
222
``` rust,ignore
220
223
#[derive(HelloWorld)]
221
224
#[HelloWorldName = "the best Pancakes"]
@@ -232,8 +235,8 @@ If we try to compile this though, the compiler will respond with an error:
232
235
error: The attribute ` HelloWorldName` is currently unknown to the compiler and may have meaning added to it in the future (see issue # 29642)
233
236
` ` `
234
237
235
- The compiler needs to know that we handle this attribute and to not respond with an error.
236
- This is done in the ` hello-world-derive` - crate by adding ` attributes` to the ` proc_macro_derive` attribute:
238
+ The compiler needs to know that we' re handling this attribute and to not respond with an error.
239
+ This is done in the `hello-world-derive` crate by adding `attributes` to the `proc_macro_derive` attribute:
237
240
238
241
```rust,ignore
239
242
#[proc_macro_derive(HelloWorld, attributes(HelloWorldName))]
@@ -244,11 +247,11 @@ Multiple attributes can be specified that way.
244
247
245
248
## Raising Errors
246
249
247
- Let' s assume that we do not want to accept `Enums` as input to our custom derive method.
250
+ Let' s assume that we do not want to accept enums as input to our custom derive method.
248
251
249
252
This condition can be easily checked with the help of ` syn` .
250
- But how to we tell the user, that we do not accept `Enums`.
251
- The idiomatic was to report errors in procedural macros is to panic:
253
+ But how do we tell the user, that we do not accept enums ?
254
+ The idiomatic way to report errors in procedural macros is to panic:
252
255
253
256
` ` ` rust,ignore
254
257
fn impl_hello_world(ast: & syn::MacroInput) -> quote::Tokens {
@@ -257,14 +260,14 @@ fn impl_hello_world(ast: &syn::MacroInput) -> quote::Tokens {
257
260
if let syn::Body::Struct(_) = ast.body {
258
261
// Yes, this is a struct
259
262
quote! {
260
- impl HelloWorld for #name {
263
+ impl HelloWorld for # name {
261
264
fn hello_world () {
262
265
println! (" Hello, World! My name is {}" , stringify! (# name));
263
266
}
264
267
}
265
268
}
266
269
} else {
267
- //Nope. This is an Enum. We cannot handle these!
270
+ //Nope. This is an Enum. We cannot handle these!
268
271
panic! (" #[derive(HelloWorld)] is only defined for structs, not for enums!" );
269
272
}
270
273
}
0 commit comments