Hacker News new | ask | show | jobs
by _ph_ 1639 days ago
Yes, calling into C from Go has a performance overhead. You wouldn't do that for trivial C functions, porting those to Go is usually the better choice and gives the better performance.

For non-trivial functions, which take some time to run, it should be mostly neglible. I also cannot see, why cgo would be "discouraged". If you have the alternative to use a Go or a C library, using the Go library is of course preferrable, but usually you don't have that choice. There are plenty of nontrivial libraries which cannot reasonably be ported to Go, which you can only use via cgo. It is usually not a good idea to try to port a complex and very actively supported C library to Go and try to maintain a fork. Also, if you have a very mixed-language project, you want to use the C library anyway from the non-Go languages. There are many very good reasons and that is why cgo is so important to have around.

It also works the other way around: you can export Go functions with C linkeage, so you can write shared libraries in Go which can be called from C. If you have a larger code base which can be extended with shared libraries as a plug-in mechanism, you can write those libraries in Go. I have done this and really like this, as writing in Go is so much nicer and more robust than in C.

1 comments

I don't know why a general observation and citation is getting downvoted.

Discouraged doesn't mean banned. It means avoided.

Regarding why, the article speaks to that.

You are right, in some cases, your best option will be cgo. That's fine. That's why it exists. It just shouldn't be someone's go-to anymore than goto is your go-to for flow control. Will you find circumstances for it? Sure. Do you want people to use it unnecessarily?

I didn't want to claim that you should use C libraries when you don't have to. But I knew the article, and it underestimates the value of being able to use libraries which are already there. Rewriting them is often not practical or even possible.
I didn't read it that way myself.

For HN comment readers that skip citations (I'm not saying you did, just helping the conversation):

First paragraph

> cgo is an amazing technology which allows Go programs to interoperate with C libraries. It’s a tremendously useful feature without which Go would not be in the position it is today. cgo is key to ability to run Go programs on Android and iOS.

Last paragraph

> To be clear, I am not saying that you should not use cgo. But before you make that Faustian bargain, please consider carefully the qualities of Go that you’ll be giving up in return.

I don't see this as devaluing.