Type Safety – GO vs C Pointers Comparison

cgopointersprogramming-languagestype-safety

C is a static-typed language that is not type-safe, because pointers(void *y) let you do pretty much anything you like, even things that will crash your program.

GO is also a static typed language

Despite, GO has pointers(var y *int), it is still considered type-safe language.


Question:

Considering GO pointers,

Why GO language is called type-safe language?

Best Answer

There are a few differences between Go and C that makes the former at least more type safe:

  1. Unless you muck about with the unsafe package, you're not going to crash a Go program (in the sense that it won't do something that causes the OS to kill it). You may cause it to panic, but this is not the same thing as a crash (and it is recoverable).

  2. Go does not have pointer arithmetic (source) -- although it does have null reference of sort called nil.

  3. Go's void* equivalent, interface{}, is cast in a more safe manner using type assertions, which will not just crash and permit safer type testing, or type switches.

Basically Go and languages with similar mixes of declared types and runtime types (C# and Java) are type safe because they supplement an unsound type system with a runtime type system that turns type errors that would have caused crashes into runtime exceptions.

C has an unsound type system and no runtime system that would prevent unsafe behavior.

Some languages, like ATS, also like runtime protections but are type-safe because their type systems make illegal operations unsayable.

Basically: type safe means the language won't let you do anything illegal.

Sometimes the runtime stops you (like in dynamic languages like Python).

Sometimes the type system stops you.

For Go it is a combination of both.

Related Topic