4.1 变量 (Variables)

Variables in Sway are immutable by default. This means that, by default, once a variable is declared, its value cannot change. This is one of the ways how Sway encourages safe programming, and many modern languages have this same default. Let's take a look at variables in detail.

Sway中的变量默认是 不可变 immutable 的。这意味着,默认情况下,一旦一个变量被声明,其值就不能改变。这是Sway鼓励安全编程的方式之一,许多现代语言也有同样的默认。让我们来看看变量的详细情况。

声明一个变量 (Declaring a Variable)

Let's look at a variable declaration:

让我们看一下变量声明:

let foo = 5;

Great! We have just declared a variable, foo. What do we know about foo?

很好! 我们刚刚声明了一个变量,foo。我们对foo有什么了解?

  1. It is immutable. 它是不可变的。

  2. Its value is 5. 它的值是5

  3. Its type is u64, a 64-bit unsigned integer. 它的类型是u64,一个64位无符号整数。

u64 is the default numeric type, and represents a 64-bit unsigned integer. See the section Built-in Types for more details.

u64是默认的数字类型,代表一个64位无符号整数。更多细节见内置类型一节。

We can also make a mutable variable. Let's take a look:

我们也可以制作一个可变的变量。让我们看一下:

let mut foo = 5;
foo = 6;

Now, foo is mutable, and the reassignment to the number 6 is valid. That is, we are allowed to mutate the variable foo to change its value.

现在,foo是可变的,重新分配给数字6是有效的。也就是说, 我们被允许 mutate 变量foo来改变它的值。

类型注释 (Type Annotations)

A variable declaration can contain a type annotation. A type annotation serves the purpose of declaring the type, in addition to the value, of a variable. Let's take a look:

一个变量声明可以包含一个 类型注释。类型注释的作用是,除了变量的值之外,还要声明其类型。让我们来看看:

let foo: u32 = 5;

We have just declared the type of the variable foo as a u32, which is an unsigned 32-bit integer. Let's take a look at a few other type annotations:

我们刚刚声明了变量foo的_类型为u32,是一个无符号的32位整数。让我们来看看其他一些类型注释:

let bar: str[4] = "sway";
let baz: bool = true;

If the value declared cannot be assigned to the declared type, there will be an error generated by the compiler.

如果声明的值不能被分配给声明的类型,编译器会产生一个错误。

Last updated