4 Making fields public with attribute macros

 

This chapter covers

  • Understanding the differences between derive macros and attribute macros
  • Finding field information in the abstract syntax tree
  • Retrieving fields by using matching
  • Retrieving fields with a custom struct
  • Retrieving fields with a custom struct and a Parse implementation
  • Adding multiple outputs in quote
  • Debugging macros with log statements
  • Understanding the no-panic crate

Rust likes to hide information. A function, struct, or enum is private by default, and the same goes for the fields of a struct. This is very sensible, though occasionally slightly annoying when you have a struct that has a lot of fields that are better off being public. Data Transfer Objects (DTOs) are a classic example of this and a common pattern in many programming languages, used for transferring information between systems or different parts of a single system. Because they are a simple wrapper for information, they should not contain any business logic. And “information hiding,” a primary reason for keeping fields in a struct/class private, is not applicable when your only value is exposing the information contained in fields.

4.1 Setup of an attribute macro project

 
 

4.2 Attribute macros vs. derive macros

 
 
 
 

4.3 First steps in public visibility

 
 

4.4 Getting and using fields

 
 

4.5 Possible extensions

 
 

4.6 More than one way to parse a stream

 
 

4.6.1 Delegating tasks to a custom struct

 
 
 
 

4.6.2 Implementing the Parse trait

 
 

4.6.3 Going low, low, low with cursor

 

4.7 Even more ways to develop and debug

 
 

4.8 From the real world

 
 
 

Exercises

 
 

Summary

 
 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest