Programming Languages - Struct / Data Class
Simple classes that are used for storing data. It may be called struct
, or data class
, or case class
, or record
, depending on the language.
Struct vs tuple: Struct is similar to a tuple , but
struct
needs a name to the data structure and a name for its fields. (struct = named tuple)struct
has no order of the fields; tuple does.
C++: struct
A struct
is the same as a class
except that members in struct
s are default to public
, while members in class
es default to private
.
Go: struct
type Vertex struct {
X int
Y int
}
// create
v := Vertex{1, 2}
v2 = Vertex{X: 1} // Y:0 is implicit
v3 = Vertex{} // X:0 and Y:0
p = &Vertex{1, 2} // has type *Vertex
// set
v.X = 4
// get
fmt.Println(v.X)
Rust: struct
struct Employee {
id: i32,
name: String,
}
// create
let mut emp1 = Employee {
id : 10001,
name : String::from("Joe"),
};
Java: record
Introduced in Java 14.
public record Employee {
int id,
String name
} {}
Kotlin: data class
data class Employee(var id: String, var name: String)
// create
val employee = Employee("10001", "Joe")
Constructor, toString()
, equals()
, hashCode()
, and additional copy()
and componentN()
functions are generated automatically.
Python
namedtuple
namedtuple
is immutable
>>> Node = namedtuple('Node', 'val left right')
>>> Node = namedtuple('Node', ['val','left','right'])
>>> Node.__new__.__defaults__ = 0, None, None
>>> Node()
Node(val=0, left=None, right=None)
dataclass
dataclass
was added in 3.7
@dataclass
decorator and they are supposed to be "mutable namedtuples with default"
Scala
Scala provides case class
:
case class Field(
name: String,
count: Option[Long]
)