##### initialize class instance #####classPoint:def__init__(self,x,y):self.x=xself.y=yp=Point(1,2)##### intialize array #####arr=[Point(1,2)]*10# use list algorithmic operatorarr=[Point(1,2)for_inrange(10)]# use list comprehension
///// initialize struct instance /////
typedefstructPoint{doublex,y;}Point_t;// declare and initialize
Point_tp;p.x=1;p.y=2;// bracket initialization
Point_tq={1,2};Point_tr={.x=1,.y=2};// initialize on heap
Point_t*s=(Point_t*)malloc(sizeof(Point_t));s->x=1;s->y=2;///// initialize array /////
Point_tarr[10];// declare without initialization
Point_tarr2[5]={{.x=1,.y=2},{.x=3,.y=4}};// initializer, here the third value is uninitialized
Point_tarr3[]={{.x=1,.y=2}};// the size of array is inferred to be 1
Point_tarr4[5]={{.x=1,.y=2},[1...4]={.x=3,.y=4}};// range initialize 2nd ~ 5th item
intarr_2d[3][3]={1,2,3,4,5,6,7,8,9};// you can even initialize 2D array with bracket initialization
intarr2_2d[3][3]={{1,2,3},{4,5,6},{7,8,9}};// declare the array on heap with 5 items
Point_t*arr5=(Point_t*)malloc(5*sizeof(Point_t));free(arr5);
///// initialize class instance /////
classPoint{public:doublex,y;// C++ will create default constructors with no args, field args and initializer list
};// declare and initialize
Pointp;p.x=1;p.y=2;// direct initialize
Pointq(1,2);// initializer
Pointr{1,2};// list initializer (C++11)
Points{.x=1,.y=2};// aggregate initializer (C++20)
// initialize on heap
Point*t=newPoint(1,2);Point*u=newPoint{1,2};///// initialize array /////
// C++ supports all initialization method from C, but you might need C++11/20
// declare the array on heap with 5 items
Point*arr=newPoint[5]{{1,2}};// all initializer syntax can be used here
delele[]arr;
///// initialize class instance /////classPoint{publicdoubleX{get;set;}publicdoubleY{get;set;}Point(){}Point(doublex,doubley){X=x;Y=y;}}// declare and initializePointp=newPoint();p.x=1;p.y=2;// constructorPointq=newPoint(1,2);Pointr=newPoint{X=1,Y=2};// anonymous typevars=new{X=1,Y=2};///// initialize array /////Point[]arr=newPoint[3];// new array with null values (or default value for struct type)Point[]arr2=newPoint[3]{p,q,r};Point[,]arr2d=newPoint[2,2]{{p,q},{r,r}};// initialize 2d arrayvarnumbers=newDictionary<int,string>// initialize object with indexers{ [7]="seven", [9]="nine", [13]="thirteen"};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
///// initialize struct instance /////
structPoint{x: f64,y: f64}letp=Point{x: 1.,y: 2.};// rust don't automatically cast the type
letq=Point{x: 2.,..p};// partial copy from another instance
letx=2.;letr=Point{x,y: 2.};// using the variable with the same name in scope
///// initialize array /////
let_: [u8;3]=[1,2,3];letarr: [Point;3]=[p,q,r];
# usually people follow certain style (like all uppercase) to name the constant variableSOME_CONSTANT=1
1
2
constintSOME_CONSTANT=1;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// constexpr is used for compile time constant
constexprintSOME_CONSTANT=1;constexprintconstexpr_func(){return1;}// const can be used to describe class members
classCoords{voidshift(constCoords&offset);doublesum()const{return_x+_y;};constdouble_x,_y;Coords(doublex,doubley):_x(x),_y(y){}// const field must be initialized using initializer list
}// const variables are only able to call const member function
constCoordscoord;coord.sum();// coord.shift() is illegal here
// `const` is used for compile time constantconstintSOME_CONSTANT=1;classSomeType{publicconstintconst_field=1;// the value still need to be defined in compile timeprivatereadonlystringconst_field2;SomeType(stringstr_in){const_field2=str_in;}// readonly field must be initialized in declaration or constructor}// since C# 7.2, readonly can be used to declare immutable typepublicreadonlystructCoords{publicCoords(doublex,doubley){X=x;Y=y;}publicdoubleX{get;init;}publicdoubleY{get;init;}publicreadonlydoubleSum(){returnX+Y;}// C# 8.0}// alternatively readonly can be applied to properties individuallypublicstructCoords{publicCoords(doublex,doubley){_x=x;Y=y;}privateint_x;publicdoubleX{readonlyget=>_x;}publicreadonlydoubleY{get;init;}// C# 9.0}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// use `const` for compile time constant
constSOME_CONSTANT: u32=1;letsome_constant=1;// immutable by default
letsome_constant=2;// this will shadow the previous definition
structCoords{x: f64,y: f64}implCoords{fnsum(&self)-> f64{// the instance is also immutable in methods
self.x*self.y}fnoffset(&mutself,Coordsoffset){self.x+=offset.x;self.y+=offset.y;}}
# variables defined in global are global variablescounter=0defsome_func():print(counter)# global vars are available in the current moduledefsome_func_mod():globalcounter# you need `global` keyword to modifycounter+=1classPlayer:def__init__(self,id):self._id=idcounter=0# member defined in class is actually a static member@staticmethoddefcreate_player():player=Player(counter)counter+=1returnplayer
1
2
3
// variables defined in global are global variables
intcounter=0;
intcounter=0;// this is a global variable
namespacesub{intsub_counter=0;// this is a global variable, but here "global" is a namespace
staticintcounter2=0;// rarely used, static here means the variable is local to this compliation unit (this source file)
}classPlayer{intid=0;// static members of a class
staticintcounter=0;staticPlayercreate_player(){returnPlayer{counter++};}// static variable can be inside a function
staticPlayercreate_player2(){staticintcounter2=0;returnPlayer{counter2++};}}
// there is no global variable, you have to tie the variable to a class.// But note that const variable can be in global scope, and you don't need to declare it as staticstaticclassUtility{staticintcounter=0;staticreadonlyintsome_constant;staticUtility(){some_constant=1;// the static constructor can be used to assign value to static readonly object}}classPlayer{Player(intid){}privatestaticintcounter=0;publicstaticPlayercreate_player(){returnnewPlayer(counter++);}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// you need static keyword to declare global/static variables
staticsome_constant: i32=1;staticmutcounter: i32=0;structPlayer(i32);fncreate_player()-> Player{println!("{}",some_constant);// read constant static variable is safe
unsafe{// read and write to mutable static variable is unsafe in rust
counter+=1;}returnPlayer(counter)}
# normal functiondefadd(a,b):returna+bfunc=add# function is also an object# closure, usually used in decoratorsdefclosure():some_value=2defincrease(x):returnsome_value+xreturnincreasefunc=closure()# lambda function (which is a closure)prefix="INFO:"log_handler=lambdax:print(prefix+x)
1
2
3
4
5
6
7
8
9
// normal function
intadd(inta,intb){returna+b;}// function pointers
int(*fn_ptr)(int,int)=&add;int(const*fn_cptr)(int,int)=&add;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// normal function
intadd(inta,intb){returna+b;}// function pointers are also supported in C++
// note that the syntax can be much more complex in C++ than in C
int(*fn_ptr)(int,int)=&add;int(const*fn_cptr)(int,int)=&add;// std::function is a safer pointer implementation
// (since C++11, you can use boost::function before C++11)
std::function<int(int,int)>func=add;// lambda function (which is a closure, since C++11)
std::stringprefix="INFO:";autolog_handler=[&prefix](std::stringx){std::cout<<prefix<<x;}std::function<void(std::string)>func2=log_handler;
// normal functionintadd(inta,intb){returna+b;}// delegates are function pointer types in C#publicdelegateintAddFunc(inta,intb);AddFuncfunc=add;System.Func<int,int,int>func2=add;// there are also predefined delegates// C# also provides Event to handle a chain of functions// (usually used in GUI applications)publiceventAddFuncaddEvents;addEvents+=func;// lambda function in C#, note that the types of parameter and return value// are decided by the function type signaturestringprefix="INFO:";System.Func<string,void>log_handler=(x)=>Console.WriteLine(prefix+x);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// normal function
fnadd(a: i32,b: i32)-> i32{a+b}// function pointer has type `fn`
letfunc: fn(i32,i32)-> i32=add;// define and return closure
// You need to wrap closure with Box in order to return it since the size of closure is unknown for compiler
fnclosure()-> Box<dynFn(i32)-> i32>{letsome_value=2;letincrease: Fn(i32)-> i32=|x|some_value+x;Box::new(increase)}letfunc_boxed=closure();
importasyncio# define and use async functionasyncdefio_task():print("fake io processing...")awaitasyncio.sleep(1)# launch the task in the current threadasyncio.get_event_loop().run_until_complete(io_task())
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// before C++20
#include<future>#include<thread>boolio_task(){std::cout<<"fake io processing\n";std::this_thread::sleep_for(std::chrono::seconds(1));returntrue;}std::future<bool>fut=std::async(io_task);// start a thread to run the task
boolresult=fut.get();// wait for the result
// co_await has been introduced in C++20, but it's still not ready to use
1
2
3
4
5
6
7
8
9
10
11
12
13
usingSystem.Threading.Tasks;asyncTaskio_task(){// the return type for async functions is void / Task / Task<T>. For WinRT, you'll need IAsyncOperation in place of TaskConsole.WriteLine("fake io processing...");awaitTask.Delay(1000);}io_task().Wait();// start the coroutine and wait for its completion, very intuitiveasyncvoidio_task_detached(){awaitio_task();}io_task_detached();// start the coroutine and don't wait for it.
1
2
3
4
5
6
7
8
9
10
11
12
usestd::time::Duration;useasync_std::task;// async function has normal return types
asyncfnio_task(){println!("fake io processing...")task::sleep(Duration::from_secs(1)).await;}// async block returns a Future<T> object
task::block_on(async{io_task()})