Overview
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Single line comment
// Single line comment
Multi-line comment
/* Multi-line
comment */
Package: every source file begins with a package clause. 'main' denotes an executable, not a library
package main
package in the Go standard library
import "fmt"
Implements some I/O utility functions
import "io/ioutil"
Import with alias m
import m "math"
Package in the github.com/google/uuid library
import "github.com/google/uuid"
Variable declaration
var x int
Variable assignment
var x int
x = 8
Variable assignment with type
var x uint = 8
Short declaration
x:=8
Multiple return values
sum, prod := sum(x, y)
String
str := "Hello, World!"
Multiline string
str := `A "raw" string literal
can include line breaks.`
String interpolation
message := fmt.Sprintf("Hello, my name is %s", name)
Rune, an alias for int32, represents a Unicode code point
g := 'Σ'
Float64
f := 3.14159
Complex128: represented internally with 2 float64's
c := 3 + 4i
Conversion syntax
n := byte('\n')
Byte slice
bs := []byte("hello")
Array initialization with 0's
var arr [4]int
Array initialization with values
arr := [...]int{3, 1, 8, 88, 100}
Copy of arr, 2 separate instances
arr_copy := arr
Update value at index 0, only arr_copy is affected
arr_copy[0] = 8
2D array declaration with 0's
var d2 [][]float64
Slice initialization with 0's
sl := make([]int, 4)
Slice initialization with values
sl := []int{4, 8, 9}
Copy of slice. Both variables point to the same instance therefore update both
sl_copy := sl
sl_copy[0] = 8
Append to slice
sl = append(sl, 8)
Append another slice
sl = append(sl, []int{8, 9}...)
Pointer
p := 5
fmt.Println(*p)
Unused variable
_ := myFunc()
Map initialization
m := map[string]int{"3": 3, "4": 4}
m["1"] = 1
Variadic parameters function input
func myFunc(x...int) {}
Variadic parameters passing to function
myFunc(arr...)
AND
x := x & y
x &= y
OR
x := x | y
x |= y
XOR
x := x ^ y
x ^= y
Shift left
x := x << y
x <<= y
Shift right
x := x >> y
x >>= y
Bit clear (AND NOT)
/*
clears bits in the first operand
where corresponding bits in the second operand are set (equal to 1),
while leaving the bits unchanged
where corresponding bits in the second operand are clear (equal to 0)
*/
x := x &^ y
x &^= y
Main function
func main() {}
Custom function declaration
func myFunc() {}
Function with parameters
func myFunc(x int) {}
Function with return
func myFunc() int {}
Function with multiple return
func sum(x, y int) (sum, prod int) {
return x + y, x * y
}
Function with named return
func sum(x, y int) (sum int) {
sum = x + y
return
}
Call function
myFunc()
Call function with parameters
myFunc(8)
Closure initialization
x := func() bool {
return x > 1000
}
Closure call
x()
Closure inline
x := func() bool { return x > 1000 }()
Anonymous function
func(a, b int) int {
return (a + b) * 2
}(8, 2)
Defer statements execute function calls in reverse order after the surrounding function returns, commonly used for tasks like file closure to keep related operations close in code
defer myFunc()
Decorators
func myFunc(str string) func(before, after string) string {
return func(before, after string) string {
return fmt.Sprintf("%s %s %s", before, str, after)
}
}
If statement
if true {}
If-else statement
if true {} else {}
Switch statement
x := 48.0
switch x {
case 0:
case 1, 2:
case 48:
case 49:
// Unreached.
default:
}
Type switch statement
var data interface{}
data = ""
switch c := data.(type) {
case string:
fmt.Println(c, "string")
case int64:
fmt.Printf("%d int64\n", c)
default:
}
For statement
for x := 0; x < 3; x++ {
fmt.Println(x)
}
For statement with break
for x := 0; x < 3; x++ {
if x == 1 {
break
}
fmt.Println(x)
}
For statement with continue
for x := 0; x < 3; x++ {
if x == 1 {
continue
}
fmt.Println(x)
}
For statement with range. Range is used to iterate over an array, a slice, a string, a map, or a channel
for key, value := range map[string]int{"1": 1, "2": 2, "3": 3} {
fmt.Printf("key=%s, value=%d\n", key, value)
}
Interface initialization
type myInterface interface {
myMethod()
}
Interface implementation
type myInterface interface {
myMethod()
}
class myClass implements myInterface {
myMethod() {
fmt.Println("myMethod")
}
}
Struct initialization
type myStruct struct {
myField int
}
Ok idiom
m := map[int]string{8: "8"}
if x, ok := m[1]; ok {
fmt.Print(x)
} else {
fmt.Print("missing")
}
Error idiom
if _, err := myFunc(); err != nil {
fmt.Println(err)
}
Panic: throw an error
panic("error")
Recover: catch an error
if err := recover(); err != nil {
fmt.Println(err)
}
Goroutine
go myFunc()
Channel initialization
c := make(chan int)
Channel
func inc(i int, c chan int) {
c <- i + 1
}
Channel send inline
c <- 8
Channel send function
go inc(8, c)
Channel receive
x := <-c
bool - Boolean
true
string - UTF-8 string
"Hello, World!"
byte - Byte (8-bit) - alias for uint8: 0 to 255(2⁸ - 1)
0
int8 - Signed Integer (8-bit): -128(-2⁸) to 127(2⁸ - 1)
-0
uint8 - Unsigned Integer (8-bit): 0 to 255(2⁸ - 1)
0
int16 - Signed Integer (16-bit): -32768(-2¹⁶) to 32767(2¹⁶ - 1)
-0
uint16 - Unsigned Integer (16-bit): 0 to 65535(2¹⁶ - 1)
0
int32 - Signed Integer (32-bit): -2147483648(-2³¹) to 2147483647(2³¹ - 1)
-0
uint32 - Unsigned Integer (32-bit): 0 to 4294967295(2³¹ - 1)
0
int64 - Signed Integer (64-bit): -9223372036854775808(-2⁶³) to 9223372036854775807(2⁶³ - 1)
-0
uint64 - Unsigned Integer (64-bit): 0 to 18446744073709551615(2⁶³ - 1)
0
int - Signed Integer (32/64-bit) - platform dependent
0
uint - Unsigned Integer (32/64-bit) - platform dependent
0
uintptr - Unsigned Integer (pointer size) - platform dependent
0xc82000c290
rune - Rune - alias for int32: represents a Unicode code point
0
float32 - 32-bit floating point: -3.4028234663852886e+38 to 3.4028234663852886e+38
0.0
float64 - 64-bit floating point: -1.7976931348623157e+308 to 1.7976931348623157e+308
0.0
complex64 - 32-bit complex number: -3.4028234663852886e+38 to 3.4028234663852886e+38
complex(8,-5)
complex128 - 64-bit complex number: -1.7976931348623157e+308 to 1.7976931348623157e+308
complex(8,-5)
- break
- case
- chan
- const
- continue
- default
- defer
- else
- fallthrough
- for
- func
- go
- goto
- if
- import
- interface
- map
- package
- range
- return
- select
- struct
- switch
- type
- var
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Single line comment
// Single line comment
Multi-line comment
/* Multi-line
comment */
JavaDoc comment
/**
* @author Name (and contact information such as email) of author(s).
* @version Current version of the program.
* @since When this part of the program was first added.
* @param For describing the different parameters for a method.
* @return For describing what the method returns.
* @deprecated For showing the code is outdated or shouldn't be used.
* @see Links to another part of documentation.
*/
Package organizes Java classes into namespaces (groups), providing a unique namespace for each type it contains
package org.example
Single namespace
import java.util.ArrayList;
Import static class
import static java.lang.Math.PI;
Import all classes inside of the package
import java.util.*;
Variable
var x = 1;
Declare variable
int x;
Declare multiple variables
int x, y, z;
Variable initialization
int x = 0;
Multiple variable initialization
int x, y, z;
x = y = z = 1;
Multiple variable initialization inline
int x = 1, y = 2, z = 3;
Byte
byte x = 1; // primitive
Byte y = 1; // object
Short
short x = 1; // primitive
Short x = 1; // object
Integer
int = 1; // primitive
Integer x = 1; // object
Long
long x = 1L; // primitive
Long x = 1L; // object
Float
float x = 1.0f; // primitive
Float x = 1.0f; // object
Double
double x = 1.0; // primitive
Double x = 1.0; // object
Character
char x = 'a'; // primitive
Character x = 'a'; // object
Boolean
boolean x = true; // primitive
Boolean x = true; // object
BigInteger
BigInteger x = new BigInteger("1");
BigDecimal
BigDecimal x = new BigDecimal("1");
String
String x = "Hello, World!" // string pool
String x = new String("Hello, World!"); // heap
Multiline string
String x = "Hello,
World!";
String interpolation
String x = String.format("Hello, %s!", "World");
Variadic parameter
void myFunc(int... numbers) {}
Variadic usage
myFunc(1, 2, 3, 4, 5);
Object declaration
Object obj = new Object();
Array declaration
int[] nums = new int[3];
Map declaration
Map<String, Integer> myMap = new HashMap<>();
Set declaration
Set<Integer> mySet = new HashSet<>();
Collection initialization
List<Integer> nums = Arrays.asList(1, 2, 3);
AND
int x = x & y;
int x &= y;
OR
int x = x | y;
int x |= y;
XOR
int x = x ^ y;
int x ^= y;
Signed shift left
int x = x << y;
int x <<= y;
Signed shift right
int x = x >> y;
int x >>= y;
Shift right unsigned
int x = x >>> y;
int x >>>= y;
Shift left unsigned
int x = x >>> y;
int x >>>= y;
Complement (invert all bits)
int x = ~y;
Main function
public static void main(String[] args) {}
Custom function declaration
public void myFunc() {}
Function with parameters
public void myFunc(int x) {}
Function with return
public int myFunc() {}
Function throws (propagates) exception to the next function
public void myFunc() throws Exception {}
Generic function declaration
public <T, R> R myFunc(T x) {}
Generic function call
String str = myFunc<Integer, String>(1);
If statement
if (true) {}
If-else statement
if (true) {} else {}
Ternary operator
int x = true ? 1 : 0;
Switch statement
switch(number) {
case 1:
case 2:
break;
case 3:
System.out.println(3);
break;
default:
System.out.println(-1);
}
For statement
for (int x = 0; x < 3; x++) {}
For statement with break
for (int x = 0; x < 3; x++) {
if (x == 1) break;
}
For statement with continue
for (int x = 0; x < 3; x++) {
if (x == 1) continue;
}
For statement with range
for (int num: nums) {
System.out.println(num);
}
While statement
while (true) {}
Do-while statement. Will run at least once
do {} while (true);
Class declaration
class MyClass {}
Interface declaration
interface MyInterface {}
Enum declaration
enum MyEnum {}
Class inheritance
class MyClass extends MySuperClass {}
Interface implementation
class MyClass implements MyInterface {}
Nested class
class Outer {
class Inner {}
}
Generic class
class MyClass<T> {}
Generic class usage
MyClass<String> myClass = new MyClass<String>();
Generic enum
enum MyEnum<T> {}
Generic interface
interface MyInterface<T> {}
Try-catch statement
try {
// Do something
} catch (Exception e) {
// Handle exception
}
Throw statement
throw new Exception("message");
Try-finally statement
try {
// Do something
} finally {
// Cleanup
}
Try-catch-finally statement
try {
// Do something
} catch (Exception e) {
// Handle exception
} finally {
// Cleanup
}
Try-with-resources statement
try (MyResource myResource = new MyResource()) {
// Do something
} catch (Exception e) {
// Handle exception
}
Thread
Thread thread = new Thread(() -> {
// Do something
});
thread.start();
Synchronized
synchronized (myObject) {
// Do something
}
byte - Byte: -128 to 127
0
short - Short: -32768 to 32767
0
int - Integer: -2147483648 to 2147483647
0
long - Long: -9223372036854775808 to 9223372036854775807
0L
float - Float: -3.4028235E38 to 3.4028235E38
0.0f
double - Double: -1.7976931348623157E308 to 1.7976931348623157E308
0.0
char - Character
'\u0000'
string - UTF-16 string
"Hello, World!"
boolean - Boolean
true
- abstract
- continue
- for
- new
- switch
- assert
- default
- goto
- package
- synchronized
- boolean
- do
- if
- private
- this
- break
- double
- implements
- protected
- throw
- byte
- else
- import
- public
- throws
- case
- enum
- instanceof
- return
- transient
- catch
- extends
- int
- short
- try
- char
- final
- interface
- static
- void
- class
- finally
- long
- strictfp
- volatile
- const
- float
- native
- super
- while
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
console.log("Hello, World!")
Single line comment
// Single line comment
Multi-line comment
/* Multi-line
comment */
Importing an entire module (ES6 modules)
import fs from 'fs'
Importing specific functions or variables from a module (ES6 modules)
import { readFile } from 'fs'
Importing an entire module (CommonJS modules)
const fs = require('fs')
Importing specific functions or variables from a module (CommonJS modules)
const { readFile } = require('fs')
var: defines a variable with function or global scope, allowing redeclaration and reassignment
var x = 0
let: Declares block-scoped variables that can be reassigned
let x = 0
const: Declares variables with block scope whose values cannot be reassigned or redeclared
const x = 0
null
x = null
undefined
x = undefined
Boolean
x = true
Number
x = 0
y = 0.0
BigInt
x = 0n
string
x = "Hello, World!"
y = 'Hello, World!'
string interpolation
x = "World"
y = `Hello, ${x}!`
Symbol
x = Symbol("x")
Infinity
x = Infinity
y = -Infinity
NaN
x = NaN
Array
x = [1, 2, 3]
2D array
x = [[1, 2, 3], [4, 5, 6]]
Object (associative array / dictionary / map)
x = { a: 1, b: 2, c: 3 }
Object access (subscript)
x["a"]
Object access (dot)
x.a
Variadic arguments
function sum(...numbers) {}
Variadic arguments usage
sum(1, 2, 3, 4, 5)
Destructuring assignment
const { x, y } = { x: 1, y: 2 }
Spread operator
x = [...[1, 2, 3]] // output: [1, 2, 3]
AND
const x = x & y
const x &= y
OR
const x = x | y
const x |= y
XOR
const x = x ^ y
const x ^= y
NOT
const x = ~x
Left shift (preserve sign bit)
const x = x << y
const x <<= y
Right shift (preserve sign bit)
const x = x >> y
const x >>= y
Zero-fill right shift (fills vacant bits with zeros regardless of sign)
const x = x >>> y
const x >>>= y
Function declaration
function myFunc() {}
Function expression (arrow function)
const myFunc = () => {}
Function with parameters
function myFunc(x, y) {}
Function call
x = myFunc(1, 2)
IIFE: Immediately invoked function expression
(function() {})(); // function declaration
(() => {})(); // arrow function
Object method declaration
myObj = {
myFunc: function() {}
}
Object method call
myObj.myFunc()
If statement
if (x) {}
If-else statement
if (x) {}
else {}
Ternary operator
x ? y : z
Nullish coalescing operator
x = y ?? 0
Falsy assignment with default value
x = y || 0
Switch statement
switch (x) {
case 'A':
console.log('A');
break;
case 'B':
console.log('B');
break;
case 'C':
console.log('C');
break;
default:
}
For loop
for (let i = 0; i < 10; i++) {}
For-in loop
for (const index in arr) {}
for (const key in obj) {}
For-of loop
for (const value of arr) {}
for (const { key, value } of obj) {}
While loop
while (x) {}
Do-while loop. Will run at least once
do {} while (x);
Object declaration
const myObj = {};
Object prototype (inheritance)
myObj.__proto__ = {};
Class
class MyClass {
myField = 0;
constructor() {}
myFunc() {}
}
Try-catch statement
try {
// Do something
} catch (e) {
// Handle exception
}
Try-catch-finally statement
try {
// Do something
} catch (e) {
// Handle exception
} finally {
// Cleanup
}
Try-finally statement
try {
// Do something
} finally {
// Cleanup
}
Throw statement
throw new Error('message')
Async/Await
async function foo() { return promise; }
Await
const response = await foo();
null - Null (typeof 'object')
null
undefined - Undefined (typeof 'undefined')
undefined
boolean - Boolean
true
number - Number
0
bigInt - BigInt
0n
string - UTF-16 string
"Hello, World!"
symbol - Symbol
Symbol()
- abstract
- arguments
- await
- boolean
- break
- byte
- case
- catch
- char
- class
- const
- continue
- debugger
- default
- delete
- do
- double
- else
- enum
- eval
- export
- extends
- false
- final
- finally
- float
- for
- function
- goto
- if
- implements
- import
- in
- instanceof
- int
- interface
- let
- long
- native
- new
- null
- package
- private
- protected
- public
- return
- short
- static
- super
- switch
- synchronized
- this
- throw
- throws
- transient
- true
- try
- typeof
- var
- void
- volatile
- while
- with
- yield
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
fun main() {
println("Hello, World!")
}
Single line comment
// Single line comment
Multi-line comment
/* Multi-line
comment */
Namespace
package org.example
Import
import org.example.Foo
Import all from the specified module
import org.example.*
Import static members from the specified module
import org.example.Foo.Companion.bar
Import with an alias
import org.example.Foo as Bar
Import specific functions or variables from a module
import org.example.Foo.{bar, baz}
var: mutable variable
var x = 0
val: immutable variable
val x = 0
Null
val x: Int? = null
Byte
val x: Byte = 10
Short
val x: Short = 10
Int
val x: Int = 10
Long
val x: Long = 10L
Float
val x: Float = 10.0f
Double
val x: Double = 10.0
Char
val x: Char = 'a'
String
val x: String = "Hello, World!"
Boolean
val x: Boolean = true
Unit
val x: Unit = Unit
Array
val x: Array<Int> = arrayOf(1, 2, 3)
List immutable
val x: List<Int> = listOf(1, 2, 3)
List mutable
val x: MutableList<Int> = mutableListOf(1, 2, 3)
Set
val x: Set<Int> = setOf(1, 2, 3)
Map
val x: Map<String, Int> = mapOf("a" to 1, "b" to 2, "c" to 3)
val y = mapOf<String, Int>("a" to 1, "b" to 2, "c" to 3)
as operator: type casting
val str: String? = obj as? String
is operator: type check and smart casting
if (obj is String) { /* do something */ }
AND
val x = x and y
OR
val x = x or y
XOR
val x = x xor y
Inverse (~)
val x = x.inv()
Signed shift left
val x = x shl y
Signed shift right
val x = x shr y
Unsigned shift right
val x = x ushr y
Main function
fun main() {
println("Hello, World!")
}
Function declaration
fun myFunc() {}
Function with parameters
fun myFunc(x: Int) {}
Function with return
fun myFunc(): Int {}
Function shortcut
fun even(x: Int) = x % 2 == 0
Function throws (propagates) exception to the next function
fun myFunc() {
throw Exception()
}
Generic function declaration
fun <T, R> myFunc(x: T): R {}
Lambda
val add = { x: Int, y: Int -> x + y }
Inline function
inline fun myFunc(x: Int) {}
If
if (true) {}
Elvis operator
val x = y ?: z
Safe call operator
val x = y?.z
For loop increment
for (i in 1..10) {}
For loop increment with step
for (i in 1..10 step 2) {}
For loop decrement
for (i in 10 downTo 1) {}
forEach loop
for (x in xs) {}
For loop with break
for (i in 1..10) {
if (i == 5) break;
}
For loop with continue
for (i in 1..10) {
if (i == 5) continue;
}
While
while (true) {}
Do-while
do {} while (true)
Object declaration
val myObj = MyObject()
Class declaration
class MyClass {}
Data class declaration
data class MyDataClass(val x: Int, val y: Int)
Object (singleton)
object MyObject {}
Class with constructor
class MyClass(val x: Int, val y: Int)
Class with overloaded constructor
class MyClass(val x: Int, val y: Int) {
constructor(x: Int): this(x, 0)
}
Interface declaration
interface MyInterface {}
Enum declaration
enum class MyEnum { RED, GREEN, BLUE }
Class inheritance
class MyClass: MySuperClass {}
Interface implementation
class MyClass: MyInterface {}
Class inheritance with super constructor
class MyClass(x: Int): MySuperClass(x)
Nested class
class Outer {
class Inner {}
}
Generic class
class MyGenericClass<T>(val x: T)
Generic class usage
val x = MyGenericClass<String>("Hello")
Generic enum
enum class MyGenericEnum<T>(val value: T)
Generic interface
interface MyGenericInterface<T>
Try-catch statement
try {
// Do something
} catch (e: Exception) {
// Handle exception
}
Throw statement
throw Exception()
Try-finally statement
try {
// Do something
} finally {
// Cleanup
}
Try-catch-finally statement
try {
// Do something
} catch (e: Exception) {
// Handle exception
} finally {
// Cleanup
}
Try-with-resources statement
BufferedReader(FileReader(fileName)).use { reader ->
var line: String?
while (reader.readLine().also { line = it } != null) {
println(line)
}
}
Thread
val thread = Thread {
// Do something
}
Coroutine
val coroutine = GlobalScope.launch {
// Do something
}
Suspend function
suspend fun foo() {
// Do something
}
boolean - Boolean
false
char - Character
'\u0000'
string - UTF-16 string
"Hello, World!"
array - Array
arrayOf()
byte - Byte (8-bit): -128(-2⁸) to 127(2⁸ - 1)
0
ubyte - UByte (8-bit): 0 to 255(2⁸ - 1)
0
short - Short (16-bit): -32768(-2¹⁶) to 32767(2¹⁶ - 1)
0
ushort - UShort (16-bit): 0 to 65535(2¹⁶ - 1)
0
int - Int (32-bit): -2147483648(-2³¹) to 2147483647(2³¹ - 1)
0
uint - UInt (32-bit): 0 to 4294967295(2³¹ - 1)
0
long - Long (64-bit): -9223372036854775808(-2⁶³) to 9223372036854775807(2⁶³ - 1)
0L
ulong - ULong (64-bit): 0 to 18446744073709551615(2⁶³ - 1)
0L
float - Float: -3.4028235E38 to 3.4028235E38
0.0f
double - Double: -1.7976931348623157E308 to 1.7976931348623157E308
0.0
- as
- break
- class
- continue
- do
- else
- false
- for
- fun
- if
- in
- interface
- is
- null
- object
- package
- return
- super
- this
- throw
- true
- try
- typealias
- typeof
- val
- var
- when
- while
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
if __name__ == "__main__":
print("Hello, World!")
Single line comment
# Single line comment
Multi-line comment
''' Multi-line
comment '''
Namespace
# based on the package structure with file `__init__.py` in each folder
Import
import os
Import partially
from math import pi, ceil
Import alias
from os import path as p
Variable
x = 0
Multiple variables
x = y = z = 0
Multiple variable assignment
x, y, z = 0, 1, 2
Variadic variable assignment
x, *y, z = 0, 1, 2, 3
Variadic function parameter
def f(*args):
pass
Keyword arguments
def f(**kwargs):
pass
String
x = "Hello, World!"
Integer
x = 0
Float
x = 0.0
Complex
x = 0j
List variable assignment
x = [0, 1, 2]
Dict variable assignment
x = {"a": 0, "b": 1, "c": 2}
Set variable assignment
x = set(0, 1, 2)
Frozen set variable assignment
x = frozenset(0, 1, 2)
AND
x = x & y
OR
x = x | y
XOR
x = x ^ y
NOT
x = ~x
Left shift (preserve sign bit)
x = x << y
Right shift (preserve sign bit)
x = x >> y
Main function
def main():
print("Hello, World!")
Function declaration
def myFunc()
Function with parameters
def myFunc(x, y)
Function with return
def myFunc():
return 0
Function shortcut
def even(x): return x % 2 == 0
Lambda function
lambda x: x + 1
Generator function
def myFunc():
yield 0
If statement
if x:
print("True")
If-else statement
if x:
print("True")
else:
print("False")
While loop
while x:
print(1)
For loop (increment)
for x in range(10):
print(x)
For loop with step (increment)
for x in range(0, 10, 2):
print(x)
For loop (decrement)
for x in range(10, 0, -1):
print(x)
For loop
for x in y:
print(x)
For loop with enumerate
for index, value in enumerate(my_list):
print(index, value)
Break
for x in range(10):
if x == 5:
break
print(x)
Continue
for x in range(10):
if x == 5:
continue
print(x)
Class
class MyClass:
pass
Constructor
class MyClass:
def __init__(self):
pass
Class method decorator
class MyClass:
@classmethod
def f(cls):
pass
Static method decorator
class MyClass:
@staticmethod
def f():
pass
Property decorator
class MyClass:
@property
def f(self):
pass
Setter decorator
class MyClass:
@f.setter
def f(self):
pass
Deleter decorator
class MyClass:
@f.deleter
def f(self):
pass
List
x = [1, 2, 3]
Dictionary
x = {'key': 'value'}
x = dict(key='value')
Set
x = {1, 2, 3}
x = set([1, 2, 3])
Tuple
x = (1, 2, 3)
x = tuple([1, 2, 3])
Range
x = range(10)
Generator
x = (x for x in range(10))
Enumerate
x = enumerate(my_list)
Try statement
try:
# Do something
except:
# Handle exception
Try-except statement
try:
# Do something
except Exception as e:
# Handle exception
Try-finally statement
try:
# Do something
finally:
# Cleanup
Raise exception
raise Exception("Error")
Async
#with help of asyncio
async def myFunc():
print(1)
response = await myFunc()
Thread
import threading
def myFunc():
print(1)
thread = threading.Thread(target=myFunc())
thread.start()
Multiprocessing
import multiprocessing
def myFunc():
print(1)
process = multiprocessing.Process(target=myFunc())
process.start()
bool - Boolean
False
noneType - None Type
NoneType
str - UTF-8 string
"Hello, World!"
int - Integer
0
float - Float
0.0
complex - Complex
0j
list - List
[]
tuple - Tuple
()
range - Range
range()
dict - Dictionary
{}
set - Set
set()
frozenset - Frozen Set
frozenset()
bytes - Bytes
b""
bytearray - Bytearray
bytearray()
memoryview - Memoryview
memoryview()
- and
- as
- assert
- break
- class
- continue
- def
- del
- elif
- else
- except
- False
- finally
- for
- from
- global
- if
- import
- in
- is
- lambda
- None
- nonlocal
- not
- or
- pass
- raise
- return
- True
- try
- while
- with
- yield
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
fn main() {
println!("Hello, World!")
}
Single line comment
// Single line comment
Multi-line comment
/* Multi-line
comment */
Doc comment (support markdown notation)
/// Doc comment
Namespace
based on the package structure with file `mod.rs` in each folder
Import
use std::io::Write;
Import alias
use std::io::Write as W;
Import multiple
use std::io::{Write, Read};
Import all items in a module
use std::*;
Variable (immutable)
let x = 0;
Variable (mutable)
let mut x = 0;
Pattern matching to destructure tuples or enums
let (x, y) = (1, 2);
Shadowing
let x = 0;
let x = x + 1;
Bind variables to functions or closures
let x = |y| y + 1;
Global constant
const x: i32 = 0;
Type annotation (after a variable name using `:`)
let x: i32 = 0;
Type alias
type MyInt = i32;
Boolean
let x: bool = true;
Character
let x: char = 'a';
String
let x: &str = "hello world!";
let s: String = "hello world".to_string();
8-bit signed integer
let x: i8 = 0;
8-bit unsigned integer
let x: u8 = 0;
16-bit signed integer
let x: i16 = 0;
16-bit unsigned integer
let x: u16 = 0;
32-bit signed integer
let x: i32 = 0;
32-bit unsigned integer
let x: u32 = 0;
64-bit signed integer
let x: i64 = 0;
64-bit unsigned integer
let x: u64 = 0;
128-bit signed integer
let x: i128 = 0;
128-bit unsigned integer
let x: u128 = 0;
32-bit floating point
let x: f32 = 0.0;
64-bit floating point
let x: f64 = 0.0;
Immutable reference
let x = &y;
Mutable reference
let x = &mut y;
Dereference
let x = *y;
Immutable pointer
let x: *const i32 = y;
Mutable pointer
let x: *mut i32 = y;
AND
x = x & y
OR
x = x | y
XOR
x = x ^ y
NOT
x = !x
Left shift
x = x << y
Right shift
x = x >> y
Main function
fn main() {}
Function declaration
fn myFunc() {}
Function with parameters
fn myFunc(x: i32) {}
Function with return
fn myFunc() -> i32 {}
Generic function
fn myFunc<T>(x: T) {}
Generic function usage
let x = myFunc::<i32>(1);
Generic constraint
fn process<T: Display>(value: T) {
println!("{}", value);
}
Generic where clause
fn foo<T, U>(x: T, y: U) -> i32
where T: Display + Clone,
U: Clone + Debug
{
// Function body
}
Higher-ranked Trait Bounds (HRTBs): enable working with traits that have generic type parameters
fn print_pair<T: Debug, U: Debug>(first: T, second: U) {
println!("{:?}, {:?}", first, second);
}
If statement
if x {}
If-else statement
if x {} else {}
Match statement
match number {
1 => println!("One"),
2 | 3 => println!("Two or Three"),
_ => println!("Something else"),
}
Loop
let mut count = 0;
loop {
count += 1;
if count == 5 {
break;
}
}
While loop
let mut count = 0;
while count < 5 {
println!("Count: {}", count);
count += 1;
}
For loop
for number in 0..5 {
println!("{}", number);
}
let text = "Line 1\nLine 2\nLine 3";
for line in text.lines() {
println!("{}", line);
}
Reverse
for i in (0..=10).rev() {
println!("{}", i);
}
Loop with step
for i in (0..=10).rev().step_by(2) {
println!("{}", i);
}
Immutable struct
struct Person {
name: String,
age: i32,
}
Mutable struct
let mut person = Person {
name: String,
age: i32,
}
Tuple
let person = (String, i32);
Unit type (Empty struct)
struct EmptyStruct;
let empty = EmptyStruct;
Functions in struct
impl Person {
fn greet(&self) {
println!("Hello, my name is {}", self.name);
}
}
Enum
enum Direction {
Up,
Down,
Left,
Right,
}
Enum with associated values
enum Direction {
Up(i32),
Down(i32),
Left(i32),
Right(i32),
}
Struct with named fields
enum Period {
Quarter { year: u16 }
}
let period = Period::Quarter { year: 2000 };
Access fields via dot notation
person.age
Trait
trait Shape {
fn area(&self) -> f64;
}
Single inheritance
trait ParentTrait {
// Method signatures
}
trait ChildTrait: ParentTrait {
// Additional methods or overrides
}
Trait implementation
struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
Generic trait
trait Printable {
fn print(&self);
}
impl<T: Printable> Pair<T> {
fn print_pair(&self) {
self.first.print();
self.second.print();
}
}
Phantom data (marker type used to represent ownership of generic types)
use std::marker::PhantomData;
struct Container<T> {
data: T,
phantom: PhantomData<T>,
}
Generic default type parameters
struct Pair<T, U = i32> {
first: T,
second: U,
}
Trait with associated types
trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}
Generic struct
struct MyStruct<T> { x: T }
Generic enum
enum MyEnum<T> { A(T) }
Throw error
Err("Division by zero".to_string())
OK (success)
Ok()
Option
fn find_element(array: &[i32], target: i32) -> Option<usize> {
for (index, &item) in array.iter().enumerate() {
if item == target {
return Some(index);
}
}
None
}
Unwrap: will unwrap in it's Some or Ok, otherwise will panic
let x = Some(5);
let y = x.unwrap();
Expect: will unwrap in it's Some or Ok, otherwise will panic with custom message
let x = Some(5);
let y = x.expect("Custom message");
Unwrap or: will unwrap in it's Some or Ok, otherwise will return default value
let x = Some(5);
let y = x.unwrap_or(0);
`?` operator: shorthand for propagating errors up the call stack
fn read_file_contents(file_path: &str) -> Result<String, std::io::Error> {
let mut file = File::open(file_path)?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
Ok(contents)
}
Panic! Macro
panic!("Custom message")
Custom error
use std::error::Error;
use std::fmt;
#[derive(Debug)]
enum MyError {
CustomError(String),
}
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
MyError::CustomError(ref message) => write!(f, "Custom Error: {}", message),
}
}
}
impl Error for MyError {}
Thread
let thread = std::thread::spawn(|| {
// Do something
});
Join
let result = thread.join();
Channel for sending and receiving values
fn main() {
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let val = String::from("Hello");
tx.send(val).unwrap();
});
let received = rx.recv().unwrap();
println!("Got: {}", received);
}
Shared State Concurrency
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
Async
async fn f() -> u32 {
42
}
Await
let result = f().await;
Future
fn f() -> impl Future<Output = u32> {
async {
42
}
}
Stream
fn f() -> impl Stream<Item = u32> {
async {
42
}
}
bool - Boolean
true
char - Character
'a'
i8 - i8 signed 8-bit integer: -128(-2⁸) to 127(2⁸ - 1)
0
u8 - u8 unsigned 8-bit integer: 0 to 255(2⁸ - 1)
0
i16 - i16 signed 16-bit integer: -32768(-2¹⁶) to 32767(2¹⁶ - 1)
0
u16 - u16 unsigned 16-bit integer: 0 to 65535(2¹⁶ - 1)
0
i32 - i32 signed 32-bit integer: -2147483648(-2³¹) to 2147483647(2³¹ - 1)
0
u32 - u32 unsigned 32-bit integer: 0 to 4294967295(2³¹ - 1)
0
i64 - i64 signed 64-bit integer: -9223372036854775808(-2⁶³) to 9223372036854775807(2⁶³ - 1)
0
u64 - u64 unsigned 64-bit integer: 0 to 18446744073709551615(2⁶³ - 1)
0
i128 - i128 signed 128-bit integer: -170141183460469231731687303715884105728(-2¹²⁸) to 170141183460469231731687303715884105727(2¹²⁸ - 1)
0
u128 - u128 unsigned 128-bit integer: 0 to 340282366920938463463374607431768211455(2¹²⁸ - 1)
0
f32 - f32 32-bit floating point number
0.0
f64 - f64 64-bit floating point number
0.0
- abstract
- as
- become
- box
- break
- const
- continue
- crate
- do
- else
- enum
- extern
- false
- final
- fn
- for
- if
- impl
- in
- let
- loop
- macro
- match
- mod
- move
- mut
- override
- priv
- pub
- ref
- return
- Self
- self
- static
- struct
- super
- trait
- true
- try
- type
- typeof
- unsafe
- unsized
- use
- virtual
- where
- while
- yield
- Syntax
- Data Types
- Reserved Keywords
- Examples
- Comments
- Namespaces
- Imports
- Variables
- Bitwise Operators
- Functions
- Flow Controls
- Structures
- Error Handling
- Concurrency
Hello World
console.log("Hello, World!")
Single line comment
// Single line comment
Multi-line comment
/* Multi-line
comment */
Namespace
// based on `baseUrl` assignment in `tsconfig.json` and folder structure
Importing an entire module (ES6 modules)
import fs from 'fs'
Importing partially (ES6 modules)
import { readFile } from 'fs'
var: defines a variable with function or global scope, allowing redeclaration and reassignment
var x = 0
let: Declares block-scoped variables that can be reassigned
let x = 0
const: Declares variables with block scope whose values cannot be reassigned or redeclared
const x = 0
null
let x: number? = null
undefined
let x: number? = undefined
Boolean
const x: boolean = false
Number
const x: number = 0
UTF-16 string
const x: string = "Hello, World!"
BigInt
const x: BigInt = 0n
Symbol
const x: Symbol = Symbol()
AND
const x = x & y
const x &= y
OR
const x = x | y
const x |= y
XOR
const x = x ^ y
const x ^= y
NOT
const x = ~y
Signed shift left
const x = x << y
const x <<= y
Signed shift right
const x = x >> y
const x >>= y
Unsigned shift right (zero-fill)
const x = x >>> y
const x >>>= y
Function declaration
function myFunc() {}
Function expression (arrow function)
const myFunc = () => {}
Function with parameters
function myFunc(x: number, y: number) {}
Function call
x = myFunc(1, 2)
IIFE: Immediately invoked function expression
(function() {})(); // function declaration
(() => {})(); // arrow function
Function with return type
function myFunc(): number {}
Arrow function
const myFunc = (x: number, y: number): number => x + y
Spread operator
x = [...[1, 2, 3]] // output: [1, 2, 3]
Destructuring
const {x, y} = {x: 1, y: 2}
Default parameter
function myFunc(x = 0) {}
Rest parameter
function myFunc(x: number, ...y: number[]) {}
Generic function
function myFunc<T>(x: T) {}
Generic function usage
myFunc<number>(1)
If
if (true) {}
If-else
if (true) {} else {}
Ternary
x ? y : z
Safe call operator
x = y?.z
Nullish coalescing operator
x = y ?? 0
Falsy assignment with default value
x = y || 0
Nullable 'elvis' operator
x = y ?: 0
Switch
switch (date) {
case 1:
case 2:
case 3:
break;
case 4:
break;
default:
// default
}
While
while (true) {}
Do-while
do {} while (true)
For
for (let i = 0; i < 10; i++) {}
For-in
for (const index in arr) {}
for (const key in obj) {}
For-of
for (const value of arr) {}
for (const { key, value } of obj) {}
Array
const arr: number[] = [1, 2, 3]
Object
const obj: { x: number, y: number } = { x: 1, y: 2 }
Tuple
const tuple: [number, number] = [1, 2]
Map
const map = new Map()
Set
const set = new Set()
Class
class A {}
Interface
interface A {}
Enum
enum A { A, B, C }
Union
const union: number | string = 1
Literal
const literal = 1 | 2 | 3
Type alias
type A = number | string
Class inheritance
class A extends B {}
Interface implementation
class A implements C {}
Generic class
class A<T> {}
Generic interface
interface A<T> {}
Generic class usage
const a = new A<number>()
Try-catch
try {
// Do something
} catch (error) {
// Handle error
}
Try-catch-finally
try {
// Do something
} catch (error) {
// Handle error
} finally {
// Cleanup
}
Try-finally
try {
// Do something
} finally {
// Cleanup
}
throw an error
throw new Error('Error message')
Async
async function foo() {
// Do something
}
Await
const response = await foo();
boolean - boolean
false
number - Number
0
string - UTF-16 string
"Hello, World!"
bigInt - BigInt
0n
symbol - Symbol
Symbol()
- any
- as
- boolean
- break
- case
- catch
- class
- const
- constructor
- continue
- debugger
- declare
- default
- delete
- do
- else
- enum
- export
- extends
- false
- finally
- for
- from
- function
- get
- if
- implements
- import
- in
- instanceof
- interface
- let
- module
- new
- null
- number
- of
- package
- private
- protected
- public
- require
- return
- set
- static
- string
- super
- switch
- symbol
- this
- throw
- true
- try
- type
- typeof
- var
- void
- while
- with
- yield