Skip to main content

29  Standard traits

R8 declares standard traits in its own namespace, which a type implements with impl() like any trait. Four are Rust’s standard traits, with their Rust meaning:

Trait Method Used by
Display format(x, ...) format(), and print() for a type without a Print impl
Debug str(object, ...) str()
PartialOrd partial_cmp(x, y) <, <=, >, >=, r8partial_cmp()
From(source) from(x) r8convert(), r8converter() (Conversion)

Two are R’s host traits, for R’s own functions:

Trait Method Used by
Print print(x, ...) print()
Shape dim(x) dim(), nrow(), ncol()

Every type has the behavior of Rust’s PartialEq (==, r8equal()), Hash (r8hash(), the hash of the canonical form), Serialize and Deserialize (r8to_json(), r8from_json()), and, when its required fields have defaults, Default, without an impl.

29.1 Display

Display gives the text that format() returns and print() shows. Without an impl, a value prints its type and fields:

cv
<demo::Resampler@KFold>
  n_resamples: 10
  seed: 2026
impl(
  Display,
  Resampler,
  methods = list(
    format = function(x, ...) {
      switch(
        r8variant(x),
        KFold = sprintf("%d-fold cross-validation", x$n_resamples),
        StratSub = sprintf("%d stratified subsamples", x$n_resamples),
        Bootstrap = sprintf("%d bootstrap resamples", x$n_resamples),
        stop("unsupported resampler: ", r8variant(x))
      )
    }
  )
)
cv
10-fold cross-validation
format(Resampler@StratSub(train_p = 0.8))
[1] "10 stratified subsamples"

29.2 Print

Print writes the output itself: print() calls the impl and returns the value invisibly, and format() keeps the text of Display:

impl(
  Print,
  Resampler,
  methods = list(
    print = function(x, ...) cat("Resampler:", format(x), "\n")
  )
)

cv
Resampler: 10-fold cross-validation 
format(cv)
[1] "10-fold cross-validation"
© 2026 E.D. Gennatas