4

I read that from Go 1.4, the Go runtime is written in Go itself (rather than in C).

How is this possible? If Go programs run on top of the runtime, and the runtime is a Go program, does the runtime run on top of itself?

user200783
  • 13,722
  • 12
  • 69
  • 135
  • 2
    This question might be useful: [Writing a compiler in its own language](http://stackoverflow.com/q/193560/142162) –  Jan 13 '16 at 00:30
  • 1
    @TimCooper - Thanks, that is useful. It seems that writing a compiler for a language in that language is possible because, once bootstrapped, a compiler is able to compile itself. However, it does not seem possible to me that a runtime can support itself: for example, can a garbage collector collect its own garbage? – user200783 Jan 13 '16 at 00:38
  • 1
    Why is it hard to understand that a language can use libraries (and frameworks) written in that same language (and compiled by that same compiler)? And why would it *not* be able to do it's own garbage collection just like anything else using that language? – Ken White Jan 13 '16 at 00:55
  • don't think of go's runtime like Ruby or Java's. Go's runtime is really just a library linked in to your native app that does stuff like GC, manage network I/O, etc... vs say, Java who's runtime can't be written in java due to java lacking native compilation. – David Budworth Jan 13 '16 at 01:34
  • @KenWhite Because a runtime is not just a library. Obviously a Go runtime that provides task execution and garbage collection cannot be written using the very features. But obviously the Go team did the job and modified the language so that it provides both a low-level layer and a high-level one like Rust with Tokio where Tokio is written with Rust but your application is made of coroutines written for Tokio, not for Rust. Similarly, the Go runtime cannot be written like a Go application. – Pavel Šimerda Sep 24 '22 at 13:04

1 Answers1

6

In short: carefully.

In long: The unsafe package lets you do pointer arithmetic and arbitrary casts, which you need to implement go's gc. You avoid using the gc in the gc go code just like you do in normal go code: by using stack- or static-allocated data. The link below mentions that the mainline go compiler enforces this in the runtime via an undocumented option. Some assembly bits let you make syscalls, which lets you do everything from spawning processes to opening files.

In longer and more authoritativer: see Ian Lance Taylor (of the go team)'s post on golang-nuts.

W. Cybriwsky
  • 511
  • 3
  • 6
  • I wonder why the answer only speaks about garbage colletion when the runtime also provides an execution framework for the normal coroutine-based applications. For a programmer who doesn't work with Go like me this doesn't really explain the low and high level parts of Go in full. – Pavel Šimerda Sep 24 '22 at 13:06