I want to write the equivalent of this C# in F#:
struct Vector2 {
public readonly int X;
public readonly int Y;
public Vector2(int x, int y) {
X = x;
Y = y;
}
}
This forces the user to supply arguments to create an instance [EDIT: this is wrong for value types - all value types have a default constructor]. A default Vector2 could be provided with a static readonly field as well, i.e. Vector2.Zero.
It looks like the only way to get public fields is via the "val" keyword, but doesn't seem to let me initialize them with the default constructor, and I don't want to have two constructors:
[<Struct>]
type MyInt(value) =
val public Value : int = value;;
val public Value : int = value;;
-------------------------------^
stdin(7,32): error FS0010: Unexpected symbol '=' in member definition
I know this can be done with member bindings but this creates properties, not fields, if I understand well.
To make a struct immutable, the simple way to make all the members readonly and initializ these values via parameterized constructor. It's members should be exposed via getter fields. Above struct is immutable as there is no way to modify the initialized variable.
It's impossible to have immutability of a single field. That was an option in an ancient version of Rust (think before 0.8), but it was dropped because the rules confused a LOT of people.
After an object (or struct) is created, it can never be changed. It's immutable.
There is no way to define immutable structures in Go: struct fields are mutable and the const keyword doesn't apply to them. Go makes it easy however to copy an entire struct with a simple assignment, so we may think that passing arguments by value is all that is needed to have immutability at the cost of copying.
According to this http://msdn.microsoft.com/en-us/library/vstudio/dd233233.aspx, that could be done as
type Vector2 =
struct
val public X: int
val public Y: int
new(x: int, y: int) = { X = x; Y = y }
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With