Traits
Demonstrates code reuse mechanisms; Python and JS use mixins, Go uses embedding, Java uses default methods.
C C23
#include <stdio.h>
#include <string.h>
// C has no traits; a "convention struct + a set of name-prefixed functions" reuses methods:
// any struct providing the conventional fields (e.g. name) can call this function set
typedef struct {
char name[32];
} Person; // satisfies the Greetable convention: has a name field
// the method set of the Greetable "trait"
void greetable_greet(const Person *p) {
printf("Hello, %s", p->name);
}
int main(void) {
Person p;
snprintf(p.name, sizeof(p.name), "%s", "Alice");
greetable_greet(&p); // equivalent to calling greet() after use Greetable
return 0;
}
Hello, Alice
C++ C++26
#include <iostream>
#include <string>
#include <utility>
template <typename Derived>
struct Greetable { // CRTP: injects reusable methods into the derived class (approximates a trait)
std::string greet() const {
return "Hello, " + static_cast<const Derived*>(this)->name;
}
};
struct Person : Greetable<Person> {
std::string name;
explicit Person(std::string n) : name(std::move(n)) {}
};
int main() {
Person p("Alice");
std::cout << p.greet() << "\n";
return 0;
}
Hello, Alice
C# v11.0.100
// interface default-implementation members are callable only via the interface type, so IGreetable is used to receive
IGreetable p = new Person("Alice");
Console.WriteLine(p.Greet());
interface IGreetable { // interface default implementation (C# 8+): approximates trait-style method reuse
string Name { get; }
string Greet() => $"Hello, {Name}"; // interface method with a default implementation
}
class Person : IGreetable {
public string Name { get; }
public Person(string name) { Name = name; }
}
Hello, Alice
Go v1.27.4
package main
import "fmt"
// Go has no traits: embedding composes capabilities (method promotion)
type Greetable struct {
Name string
}
func (g Greetable) Greet() string {
return "Hello, " + g.Name
}
type Person struct {
Greetable // embedding: Person directly "has" the Greet method
}
func main() {
p := Person{Greetable: Greetable{Name: "Alice"}}
fmt.Println(p.Greet())
}
Hello, Alice
Java v27.0.1
public class Main {
// Java has no traits; interface default methods are the closest reuse mechanism
interface Greetable {
String name(); // abstract method: implementing classes provide the data
default String greet() { // default method: ships with an implementation, reusable
return "Hello, " + name();
}
}
static class Person implements Greetable {
private final String n;
Person(String n) { this.n = n; }
public String name() { return n; }
}
public static void main(String[] args) {
Person p = new Person("Alice");
System.out.println(p.greet());
}
}
Hello, Alice
JavaScript v26.13.1
// JS has no traits; functional mixins are the common way to reuse code
const Greetable = (Base) => class extends Base {
greet() {
return `Hello, ${this.name}`;
}
};
class Person extends Greetable(Object) {
constructor(name) {
super();
this.name = name;
}
}
const p = new Person("Alice");
console.log(p.greet());
Hello, Alice
PHP v8.6.0
trait Greetable { // define a trait: a set of reusable methods
public function greet(): string {
return "Hello, " . $this->name;
}
}
class Person {
use Greetable; // use the trait, effectively "pasting" its methods into this class
public function __construct(public string $name) {}
}
$p = new Person("Alice");
echo $p->greet(), "\n";
// a class may use multiple traits; same-name conflicts are resolved with insteadof
Hello, Alice
Python v3.15.2
# Python has no traits; convention is Mixin classes (a restricted form of multiple inheritance)
class GreetableMixin:
def greet(self):
return f"Hello, {self.name}"
class Person(GreetableMixin): # Mixin goes leftmost in the inheritance list
def __init__(self, name):
self.name = name
p = Person("Alice")
print(p.greet())
Hello, Alice
Rust v1.99.1
// Rust traits support default methods, making them the closest mechanism to PHP traits
trait Greetable {
fn name(&self) -> &str; // implementors only need to provide the data
fn greet(&self) -> String { // default method: ships with an implementation, reuse directly
format!("Hello, {}", self.name())
}
}
struct Person {
name: String,
}
impl Greetable for Person {
fn name(&self) -> &str {
&self.name
}
}
fn main() {
let p = Person { name: String::from("Alice") };
println!("{}", p.greet());
}
Hello, Alice
TypeScript v26.13.1
// TS has no traits; functional mixins are the common way to reuse code
const Greetable = (Base: any) =>
class extends Base {
greet(): string {
return `Hello, ${this.name}`;
}
};
class Person {
name: string;
constructor(name: string) {
this.name = name;
}
}
class GreetablePerson extends Greetable(Person) {}
const p = new GreetablePerson("Alice");
console.log(p.greet());
Hello, Alice
Language differences
C: no classes — the example holds state in a struct with prefixed functions as methods, semantics enforced by convention; the trait is emulated by "conventional fields + a function set" for horizontal reuse.
C++: no traits — CRTP (curiously recurring template pattern) achieves reuse via static polymorphism.
C#: no traits — C# 8+ default interface methods approximate reuse and are invoked through the interface type.
Go: struct embedding — the embedded type methods are promoted to the outer type.
Java: interface default methods (introduced in Java 8) are a close approximation (they can only live in interfaces).
JavaScript: functional mixins (functions returning an anonymous class extending Base).
PHP: a trait is pulled into a class with use; a class may use multiple traits, method conflicts are resolved with insteadof and aliased with as, enabling horizontal reuse under single inheritance; key differences — trait methods are copied into each using class (not inherited through a type), can reach the host class's private members, and a trait itself is not a type (it cannot be used for instanceof or type declarations).
Python: no traits — the convention is Mixin classes combined with multiple inheritance (placed on the left of the bases list).
Rust: traits combining default and abstract methods are the closest match to trait semantics; a Rust trait is a type contract (usable as a bound or a trait object), dispatches statically by default, falls under the orphan rule, and cannot carry fields.