Writing to the mutable property to write the structure is not allowed in F #. What for?

When I have the following code:

[<Struct>]
type Person = { mutable FirstName:string ; LastName : string}

let john = { FirstName = "John"; LastName = "Connor"}

john.FirstName <- "Sarah";

The compiler complains that "the value for changing the content must be changed." However, when I remove the Struct attribute, it works fine. Why is this so?

+6
source share
1 answer

This protects you from getting that hit the world a few years ago C#: structs are passed by value.

Please note that red squiggly (if you are in the IDE) appears not under FirstName, but under john. The compiler does not complain about a change in value john.FirstName, but about a change in the value itself john.

With nonstructures, there is an important difference between a link and a reference object:

enter image description here

, . (.. ), (.. ).

, , , :

enter image description here

, john.FirstName john. .

, , john :

[<Struct>]
type Person = { mutable FirstName:string ; LastName : string}

let mutable john = { FirstName = "John"; LastName = "Connor"}

john.FirstName <- "Sarah"  // <-- works fine now

#:

struct Person
{
    public string FirstName;
    public string LastName;
}

class SomeClass
{
    public Person Person { get; } = new Person { FirstName = "John", LastName = "Smith" };
}

class Program
{
    static void Main( string[] args )
    {
        var c = new SomeClass();
        c.Person.FirstName = "Jack";
    }
}

IDE c.Person , "SomeClass.Person", ".

? , c.Person, getter, , Person. Person , Person Person . , . , , Person, SomeClass.

, :

c.Person.FirstName = "Jack"; // Why the F doesn't it change? Must be compiler bug!

, . !: -)

+13

All Articles