dexscript / design

DexScript - for Better Developer EXperience
http://dexscript.com
Apache License 2.0
4 stars 0 forks source link

Symbol & Mutability #2

Open taowen opened 5 years ago

taowen commented 5 years ago

GOAL

clearly express the logic, leave the physical execution detail to compiler and runtime.

Java

class Money {
  public int Amount;
  public String Unit;
}
void transfer(final Money m) {
  // although m is final, assignment like m.Amount = 100 is still valid
}

Go

type Money struct {
  Amount int
  Unit string
}
func transfer(m Money) {
  // m is a copy
}
func transfer(m *Money) {
  // m is a reference to same value, mutable
}

Shiti

YinGuo defined two keyword var and let. Func argument is const by default, unless otherwise specified.

We do not need to worry about the argument is passed as a copy of value or reference some memory on the heap. The code should focus on the logic, not execution details.

func OpenFile(file string) File {
  // func argument is const by default
}

add var to make the func argument a variable

type Times(arr var []int, multiplier int) {
  // multiplier = 3 will compile fail, because multiplier is not variable but const
  for i, e := range arr {
    arr[i] = e * multiplier
  }
}

use let to define a const in block scope

type Times(arr var []int, multiplier int) {
  for i, e := range arr {
    let newValue = e * multiplier
    arr[i] = newValue
  }
}

variable is mutable

type Times(arr var []int, multiplier int) {
  for i, e := range arr {
    var newValue = e
    newValue = newValue * multiplier
    arr[i] = newValue
  }
}