How is it possible for the Go runtime to be written in Go?
Asked Answered
R

1

5

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?

Rhodia answered 13/1, 2016 at 0:16 Comment(5)
This question might be useful: Writing a compiler in its own languageMaurya
@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?Rhodia
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?Arrangement
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.Existentialism
@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.Mawson
P
7

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.

Provitamin answered 13/1, 2016 at 4:32 Comment(1)
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.Mawson

© 2022 - 2024 — McMap. All rights reserved.