Sunday, April 17, 2022

Go vs Rust - Basic Data Types

 Basic types include Numbers, strings and booleans.

1 Integer

长度 Rust 有符号 Rust 无符号 Go有符号 Go无符号

8-bit i8                 u8                 int8                 uint8

16-bit i16                 u16                 int16         uint16

32-bit i32                 u32                 int32         uint32

64-bit i64                 u64                 int64         uint64

128-bit i128                 u128         -                 -

arch         isize                 usize          int                 uint


byte // It is a synonym of uint8 in Go.

rune | char 
rune is a synonym of int32 and also represent Unicode code points in Go. The char type in rust is the same as the rune type in go. It represents Unicode code points, accounting for 4 bytes. When writing Unicode characters, you need to prefix \u or \U before hexadecimal numbers. Because Unicode takes at least 2 bytes, we use int16 or int type to represent it. If you need to use up to 4 bytes, use the \u prefix. If you need to use up to 8 bytes, use the \U prefix.

uintptr // It is an unsigned integer type in Go. Its width is not defined, but its can hold all the bits of a  
               pointer value.

Number literals Rust                          Go

Decimal                98_222                      98222
Hex                        0xff                            0xff
Octal                0o77                          0o77
Binary                0b1111_0000
Byte (u8 only)        b'A'                            'A' or '\x41' or 65

  • There is no 128 bit integer in Go
  • isize and usize in Rust correspond to int and uint in Go. Their length depends on the computer architecture of the running program: they are 64 bits in 64 bit architecture and 32 bits in 32-bit architecture.
  • In Go, the default type of integer variable is int.
  • In Rust, Number literals can also use _ as a visual separator to make the number easier to read, such as 1_000, which will have the same value as if you had specified 1000.


Complex Number Types

In Go there are complex64 and complex128. But Rust has no corresponding types.

var a complex128 = complex(6, 2)

Floating-Point Types

Go          Rust
float32    f32
float64    f64

Go
var x float32 = 123.78
var x float64 = 1.7e+308

Rust 
let x = 2.0; // f64
let y: f32 = 3.0; // f32

Boolean Type

bool: true or false

Go
var bVal bool   // default is false

Rust
let bool_val = true & false | false



No comments:

Post a Comment