Are value types immutable by definition?

后端 未结 12 1506
陌清茗
陌清茗 2020-12-04 09:18

I frequently read that structs should be immutable - aren\'t they by definition?

Do you consider int to be immutable?

int i         


        
12条回答
  •  春和景丽
    2020-12-04 09:42

    Objects/Structs are immutable when they are passed into a function in such a way as the data cannot be changed, and the returned struct is a new struct. The classic example is

    String s = "abc";

    s.toLower();

    if the toLower function is written so they a new string is returned that replaces "s", it's immutable, but if the function goes letter by letter replacing the letter inside "s" and never declaring a "new String", it is mutable.

提交回复
热议问题