3

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?

9

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.

4

The lack of type safety doesn't come from pointers - it comes from void pointers and the ability to perform arbitrary casts between pointer types. There's nothing non-type safe about "pointer to integer" - the lack of type safety in C comes about because there's no guarantee that an int* is actually pointing to some memory which contains an integer.

  • So, Do you mean, GO compiler does not allow type casting( like *char to *Person)? – overexchange Jan 29 '17 at 1:24
  • 3
    Correct - well, unless you're messing around with unsafe and Pointer in which case you deserve everything you get in terms of blowing up the type system. – Philip Kendall Jan 29 '17 at 1:30
  • Arbitrary casts without safety checks (or, whose only safety checks are compile-time and easily defeated). Also, lack of type safety comes from unchecked pointer arithmetic, independent of casting, as this allows moving the pointer off of what it started at; so, may end up referring to arbitrary memory. Of course, pointer arithmetic can be combined with casting! – Erik Eidt Jan 29 '17 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.