Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an immutable struct with public fields?

Tags:

f#

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.

like image 797
Asik Avatar asked Aug 08 '13 19:08

Asik


People also ask

How do you make a struct immutable in C#?

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.

Are rust structs immutable?

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.

Are structs immutable go?

After an object (or struct) is created, it can never be changed. It's immutable.

How do you make a struct immutable in Golang?

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.


1 Answers

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
like image 162
V.B. Avatar answered Oct 07 '22 00:10

V.B.