Today we learn how to change the value of variable(not variable actually)
remember how to define a value
let name = "Lucy"
can we change our name? let's try to change the value of our string variable
let name = "Lucy"
name <- "Lily"
printfn $"{name}"
the error message on the Problems window:
This value is not mutable. Consider using the mutable keyword, e.g. 'let mutable name = expression'.(2,1)</br>
obviously, change value of name is not allowed
luckily, the error message is clear and friendly, it even suggest how to fix the problem
let's try it's sugguestion:
let mutable name = "Lucy"
name <- "Lily"
printfn $"{name}"
run the code, name has been changed successfully!
conclusion:
value we define in F# is immutable by default, we need to explicitly add 'mutable' before value, now we can call it variables, as we can change it's value later
Let's do a practice:
my name is Lucy, I'm 14 year's old
let name = "Lucy"
let age = 14
printfn $"my name is {name}, I'm {age} years old"
my sister is Lily, she's 11 year's old, please introduce herself for Lily without define new values
answer:
let mutable name = "Lucy" // name is variable now
let mutable age = 14
printfn $"my name is {name}, I'm {age} years old"
name <- "Lily"
age <- 11
printfn $"my name is {name}, I'm {age} years old"
Top comments (0)