Limitations: where the seams are
So you’re about to point go2cs at your own Go code. Before you spend an evening on it, here is where it will fail, where it will fight you, and where it will quietly do something a little different from Go – better you hear it from me than from a stack trace. Specific bugs with workarounds live in Known issues. This page is the limits that come with running Go on .NET, plus the rough spots real code hits today.
The short version
Good odds tonight: pure Go that builds with the Go release go2cs tracks and CGO_ENABLED=0, leans mostly on the
standard library, and runs on Windows, Linux or macOS. A longer evening: lots of third-party modules,
unsafe, assembly fast paths, cgo, or tests that pull in testify.
- Your code must build with the Go release go2cs tracks, the one in Requirements, which the go2cs dotnet tool downloads for you.
- cgo converts only through
-cgo, and only calls of C functions a shared library defines (cgo). - Assembly,
//go:linknameand deepunsafetricks compile clean, then fail at run time. Many libraries ship a pure-Go fallback behind a build tag, and you have to pass that tag yourself. - By default, each live goroutine holds an operating-system thread. Thousands alive at once are fine; Go’s million are out of reach.
- It’s usually slower than Go, starts slower and uses more memory.
- One conversion targets one operating system.
- Most failures are loud. A few differences are silent: see the last bullet under what behaves differently.
What won’t make the trip
- cgo beyond calls of shared-library C functions: see cgo.
- A self-referential constraint over a pointer, when a method shares the element’s storage.
Walk[*Node]underWalk[N Tree[N]]withChildren() []Nstops the run witherror GO2CS2002, naming the site and the method. Two related shapes over a pointer element are refused the same way, asGO2CS2005andGO2CS2006(diagnostic codes). A pointer element reaches the generic code through a proxy object, and a[]N,map[K]N,chan Nor*Nthe proxy passed along would be a copy, not Go’s shared value. The same function over a value element converts, and so does a constraint whose methods pass onlyN, funcs and arrays (how). No Go 1.26 standard-library package reaches it. - Go newer than the library tracks. A newer
goline in yourgo.mod, or any dependency’s, getspackage requires newer Go versionor a refusal naming both releases. SetGOTOOLCHAIN=localand pin older versions untilgo build ./...passes, as the module walkthrough does. - Hand-written assembly. A function whose body lives in a
.sfile usually becomes a stub. The project builds clean, and the first call throws aNotImplementedExceptionsayingno implementation reached this compilation. Convert with the library’s pure-Go build tag (below), or write the body in C#.//go:linknameinto the runtime gets the same stub, outside a short list the converter knows. - One generics form.
type Cell[T any] = struct{ Row, Col T }, a generic alias of an anonymous struct or interface, gets a warning, and every use is a C# compile error. Name the struct instead. - Code that doesn’t type-check for the target still converts, with the literal text
invalid typewhere a type is missing (error GO2CS1003), and the C# build stops there.
What converts, but doesn’t behave exactly like Go
- Reflection cannot read a struct whose arrays are held inline. When a package reads native memory as a
struct, through
(*T)(unsafe.Pointer(p)), go2cs lays that struct out as Go does and holds its array fields inside it. Indexing,len,rangeand printing one of those arrays work as in Go. Reflection over the struct that holds them does not:fmt.Printf("%v", s),reflect.ValueOf(s).Field(i)and anything else that walks the struct’s fields panics withreflect: field T.F is a Go array held inline (go.arrays); reflection does not read or address it. Print the fields one at a time instead. - A slice of an array held inline panics when the struct around it also holds a string, a slice, a map, an interface
or a pointer. A slice of such an array (
p.ID.Data4[:2]) uses the array’s own bytes, as in Go, so go2cs holds the storage still for as long as the slice lives. It cannot hold still a struct that holds a Go reference, so the slice panics withinline array slice: an array held inline in a struct that also holds a Go reference cannot be held still, so it cannot be sliced. This is ordinary Go, and programs that use go-winio will hit it when they keep a GUID beside a string:type P struct { ID guid.GUID; name string }, thenp.ID.Data4[:2]. go-winio’s own GUID methods are not affected, because each slices its own copy of the GUID. Two forms work today: acopyinto or out of the array with constant bounds (copy(buf, p.ID.Data4[:])), and slicing a local copy of the array (d := p.ID.Data4; s := d[:2]) when writes need not reachp. - By default, goroutines are operating-system threads (why). A goroutine
holds its thread for as long as it lives; when it ends, the thread runs the next
gostatement, so starting goroutines one after another is cheap and holding many alive at once is not. On Windows x64, ten thousand parked goroutines cost several times Go’s memory and seconds to start, a hundred thousand take minutes, and a million do not finish starting. With threads,runtime.GOMAXPROCS(1)does not make anything run one at a time. Bound your fan-out with a worker pool, and remember that anet/httpserver spends one on every open connection. On macOS the kernel caps the threads one process may run (kern.num_taskthreads, a few thousand on the hosted macOS 15 machines measured), and thegostatement past it ends the program (Known issues). - A deadlock usually hangs where Go prints
all goroutines are asleep - deadlock!. The message appears only when every goroutine,mainincluded, waits on a nil channel or an emptyselect {}, and then with Go’s goroutine blocks. A deadlock on an ordinary channel or lock blocks forever: break in with a debugger, where, by default, each goroutine is a thread namedgoroutine-N. - Stacks don’t grow.
mainruns on a thread that reserves 1 GiB, which covers Go’s 1 GB limit for it, and a goroutine’s thread reserves 256 MB (GO2CS_GOROUTINE_STACKchanges it), or 16 MB when the converter proves it cannot recurse (how). Recursion past a thread’s reserve ends the process with .NET’sStack overflow., with no panic and no deferred calls, where Go printsfatal error: stack overflowand exits 2. Your main package’sinitfunctions run on the startup thread’s smaller stack, and so doesmainwhen aninitcalledruntime.LockOSThread, as in Go. recover()catches Go panics, not every .NET exception. Nil dereference, divide by zero and index out of range recover as in Go. Any other .NET exception,NotImplementedExceptionincluded, runs your deferred calls and keeps unwinding, andrecover()returns nil. As in Go,recover()stops a panic only when the deferred function calls it directly, with two exceptions (how): an exported function that callsrecover()stops the panic even when a deferred function calls it, and an unexported one that another package defers through a func value returns nil.- A crash’s traceback is sometimes shorter than Go’s. An unrecovered panic prints Go’s panic lines, the
whole chain included (
panic: message [recovered, repanicked]), and exits with status 2, a goroutine’s panic whilemainreturns included. Below them, the frames match Go’s for a panic in a function with one deferred call. When several functions on the stack each defer a call, only the function that panicked is shown, and a named deferred function that panics again shows the line it is declared on. unsafeworks over plain numbers and stops at anything .NET’s garbage collector tracks (the rules). A pointer to anything holding a string, slice, map, interface, pointer or fixed-size array gets a stand-in number, not an address, so the older tricks (the*(*string)(unsafe.Pointer(&b))pun, a hand-built slice header) don’t convert mechanically.- One array view can end the process. Go’s
(*[N]E)(unsafe.Pointer(&x.f))[:], wherefis an array field read as an array of another element type (an[8]int8name read as[8]byte), works whenxis a variable or a pointer, and through any chain of named fields from one (&x.a.f). When the field is promoted from an embedded struct (&w.f), or belongs to a slice element (&s[i].f) or to a call’s result (&g().f), the converted program can stop with an access violation, whichrecoverdoes not catch. Take the field’s address from a variable or a pointer instead: write the embedded field out (&w.inner.f), or bind the element or the result first (p := &s[i], then&p.f) (the field view). - The address of another package’s pointer- or interface-typed variable is the address of a copy. An
exported variable with a value type has its own storage, so
&otherpkg.V,f := otherpkg.V.Reset,flag.BoolVar(&otherpkg.Debug, ...)and&otherpkg.S.Fieldreach the variable itself, as in Go. Two kinds are still handed to another package as a copy when it takes their address, so a write through it never reaches the variable: a variable whose type is a pointer or an interface (&otherpkg.ErrMissing), and a variable whose storage lives somewhere else (runtime.MemProfileRate, or one declared with a two-argument//go:linkname). Reading them, assigning to them and calling their methods work. Take the address in the declaring package, or have it export an accessor (Known issues). - Garbage collection is .NET’s. An object your function just stopped using may not be collectible
until the function returns, so “drop the reference, call
runtime.GC(), expect the finalizer” can wait forever.GOGCandGOMEMLIMITare read and reported, bydebug.SetGCPercentfor example, but .NET’s collector does not follow them. - Runtime introspection is thinner than Go’s. A dump of all goroutines lists each one and what it waits on,
with frames for the calling goroutine only.
pprof.StartCPUProfilegives a profile with no samples (profile with .NET’s tools).debug.ReadBuildInfo()reports the module, its dependencies,GOOS,GOARCH,CGO_ENABLEDandDefaultGODEBUG, but no-compiler,-buildmode,GOAMD64orvcs.*settings and no replacements, and nothing for a program converted outside a module (how). On Windows,time.LoadLocation("Europe/Berlin")fails until you importtime/tzdata(or setZONEINFO). - A few quiet ones, each rare, where converted code gives a different answer and says nothing:
- A variadic function that keeps, returns or captures its
...Tparameter, orappends orcopys into it, works on a private copy: afterf(s...), its writes are not the caller’ss. - Copying a struct by value shares any fixed-size array inside an embedded struct.
- A slice of one number type laid over another’s storage
(
unsafe.Slice((*uint64)(unsafe.Pointer(&b[0])), n)) is a copy: writes through it never reachb. - A pointer’s number kept in a
uintptrand turned back into a pointer in a later statement (n := uintptr(unsafe.Pointer(p)), then(*T)(unsafe.Pointer(n))) can name memory that has since moved, and the number does not keep the value alive. Go calls this invalid too, but it often works there. Do the arithmetic and the conversion in one expression, or useunsafe.Add. - A pointer to a field made by arithmetic does not compare equal to the field’s own address:
(*int64)(unsafe.Add(unsafe.Pointer(&p), 8)) == &p.yis false where Go says true. - A left shift of an untyped constant that takes a named integer type from its context, such as
m & (1 << uint(32-1-i))withmanfs.FileMode, wraps its count at the type’s width: a count of the width or more gives the wrapped result where Go gives 0, and a negative count does not panic. - In a cgo package, a pointer into Go memory rebuilt from a number can reach C unchecked in three narrow cases (cgo).
- A variadic function that keeps, returns or captures its
cgo
What converts. Without -cgo, a package whose build selects a file with import "C" stops the run with
error GO2CS2001, which names the file. With -cgo, on a machine with a C compiler (go env CC), a package
converts when every C use it makes is a call of a C function a shared library defines, passing integers,
floating-point numbers and pointers, structs of integers and pointers by value, one struct or one scalar by
pointer, or a void * that is nil or points at C memory. C.CString, C.CBytes, C.GoString, C.GoStringN,
C.GoBytes, C.malloc, C.free and defer C.f(…) convert, with the package’s C types and constants. A
program that uses the converted package needs only the C library.
One package, one machine. A -cgo conversion is one package, for the machine’s own operating system and
architecture, and the converted package refuses to call C anywhere else. It builds against a go2cs clone
(dotnet build -p:go2csPath=<go2cs>/src/), not against the go.* packages
(Roadmap). The standard library itself is converted with CGO_ENABLED=0.
What is refused, by name, with the phase that will cover it:
- a pointer into Go memory handed to C as a
void *, or toC.GoBytes,C.GoStringorC.GoStringN(Phase 3). A pointer into a slice or an array is refused when the package is converted;unsafe.Pointer(&x)is refused when the call runs, with a message that names the call. Inside a method with a pointer receiver,unsafe.Pointer(p)of a pointer of the receiver’s own type is refused when the package is converted: move the call into a function that takes the pointer as a parameter; - a function the preamble itself defines, and a
#definethat is not a constant, both of which need compiled C (Phase 4); //export(Phase 5);- a C variable, a C function used as a value, and
go C.f(…)with a pointer cmd/cgo checks (Phase 2); - a C function Go’s own cgo build does not import by its C name: one a header renames (macOS on x64 makes
fstatthe symbolfstat$INODE64), or one the C compiler inlines. go2cs cannot tell the two apart, so it refuses both rather than bind a function C would not call:error GO2CS2001: C.abs: cmd/cgo's own binary does not import a symbol named abs, ...(Phase 2). Which functions those are depends on the compiler and the C library:absandlabseverywhere, and with glibc alsoatoi,atol,toupper,tolowerandfabs.
Where it differs from Go. go2cs never hands C a pointer into Go’s memory: it hands C a copy of the one struct a pointer points at, and copies it back after the call. So cgo’s pointer check differs from Go’s in five places, all where a program breaks or bends cgo’s pointer rules:
- Go checks a pointer held in a variable against the whole object it points into, and panics when that object also holds a Go pointer or lives in package-level memory. go2cs proceeds, since C only sees the copy. This is the check most cgo calls in the Go toolchain’s own cgo packages take.
- Go accepts a struct member that points at memory pinned with
runtime.Pinner, any pointer underGODEBUG=cgocheck=0, and a struct passed by value whose pointer member points into Go memory that holds no pointer. go2cs refuses all three when the call is made.
A known memory-safety gap: a pointer rebuilt from a number, in three narrow cases. go2cs refuses, by
name, any address inside Go memory that it is holding still, even after the address has been through a
uintptr: u := uintptr(unsafe.Pointer(p)), then unsafe.Pointer(u + n), the reversed sum
unsafe.Pointer(n + uintptr(unsafe.Pointer(p))), and a slice element viewed as another type
((*C.int)(unsafe.Pointer(&b[4]))) and then held as a uintptr. Go’s own one-expression form,
unsafe.Pointer(uintptr(unsafe.Pointer(p)) + n), converts to unsafe.Add, which go2cs refuses by name, as
it does unsafe.Pointer(p) itself. Three cases still cross, because go2cs is no longer holding the memory,
or never was. In each, the call goes ahead, and the memory may move while C uses it:
- a number kept after nothing uses
pany more. go2cs stops holding the memory still, and the number reads as C memory. Go’s own rules already forbid keeping a pointer as auintptrlike this; - a number taken inside a method with a pointer receiver, from a pointer of the receiver’s own type. go2cs
makes that number without holding the memory still. Passing such a pointer to C directly is refused when
the package is converted; taking it through a
uintptrfirst is not caught; - Go memory held still before the program’s first cgo package was loaded, which can be missing from go2cs’s record of what it holds.
Platforms. A converted cgo program was built and run against the Go build of the same program on linux/amd64, darwin/amd64, darwin/arm64 and windows/amd64, and printed what Go printed apart from the differences above.
What works, but costs you something
- Speed. In the performance comparison, measured on
win-x64, most compute lands within a small multiple of Go’s time, string-heavy work takes several times longer, maps run at parity or better, and asking at run time whether a value satisfies an interface (v.(fmt.Stringer)) is the slowest thing converted code does. Tuning converted code says which deployment and runtime settings to choose. Measure your own hot path, in Release. - Startup, memory and shipping. A converted program loads .NET and one DLL per converted Go package it uses,
and the JIT compiles each method the first time it runs; package-level tables are built when first read. You ship
a .NET app, not Go’s small static binary:
dotnet buildoutput needs the .NET 10 runtime, anddotnet publish -r <runtime>gives a self-contained folder compiled ahead of time with ReadyToRun, which starts noticeably faster (on linux-x64).dotnet runanddotnet buildnever get ReadyToRun (how). - Trimming. A converted project carries the
partialtrim mode, and a C# project you write gets the same default from the packages. A trimmed publish runs, and its output matches the untrimmed build’s. It warns (on linux-x64): one IL2104 for eachgo.*package with trim warnings, a handful for a program that usesfmt, and-p:TrimmerSingleWarn=falselists the warnings behind them, most of them golib’s,runtime’s andreflect’s use of reflection. A project built from the converted source lists them all. - Single-file and Native AOT. A single-file publish needs ReadyToRun compiled per assembly
(Known issues). Native AOT
starts much faster and holds less memory, but once running it is slower than the JIT on most rows of the
comparison (
win-x64), and a publish compiles every converted package your program references in full (Known issues has the measurements). - Allocation. Converted code allocates where Go’s compiler doesn’t, so expect more garbage and
failing
testing.AllocsPerRunassertions. - Crypto, most hashing and
math/bigrun Go’s portable code, the way Go builds with-tags purego: correct, validated, and slower than Go’s assembly. A TLS handshake is where you will notice.
Third-party modules: where they trip today
The validated modules page lists the modules validated so far.
- A dependency’s assembly converts to methods that throw when called, unless a tag deselects it.
A plain
-recurse(your module plus its dependencies) appliessafe,puregoandnoasmfor you, so a fast path behind!puregoor!noasmis replaced by the library’s pure-Go fallback (Build tags for a module). A file gated on the architecture alone has no such fallback: zeebo/xxh3’saccum_stubs_amd64.godeclares its vector routines with no body, so they convert to stubs. xxh3 calls them only when the CPU reports AVX2, AVX-512 or SSE2, which the converted klauspost/cpuid never does undernoasm, so hashing works and only code that forces a vector path on (xxh3’s own tests do) throws. An explicit-tagsreplaces every default, so includesafe,purego,noasmwith yours, and under-testsincludemath_big_pure_gotoo. - A test suite that imports testify depends on the
safetag. Its bundled go-spew does pointer arithmetic intoreflect.Valueat load, which the runtime library refuses by design, and go-spew’ssafetag selects its fallback. Drop the tag, with-module-safe-tag=falseor an explicit-tagsthat leaves it out, and the converted test program dies at startup. - A hung test is stopped, where
go testwaits. A converted test still running 15 minutes after it started is reported as a failure and marked abandoned, and the run moves on to the next test (-test-deadlinechanges the limit, Command line). Its goroutines keep running, so every later result says it ran after the abandoned test. - Converter bugs that surface as C# compile errors, usually in corners of the type system. In your
own code, reshape the Go. In a dependency, point a
replaceat a patched copy, or fix the generated.csand mark the file[module: go.GoManualConversion]so the next conversion leaves it alone. New ones still turn up: tell me. unsafeviews of a string’s or a slice’s bytes are not supported yet. Go code can read a string or a[]bytethrough its header,*(*struct{ p unsafe.Pointer; n uint })(unsafe.Pointer(&s)), and then read bytes atunsafe.Pointer(uintptr(p) + i)or through(*[8]byte)(p). Converted, these stop with a named runtime panic, because the string or slice lives in .NET-managed memory with no fixed address to offset. github.com/zeebo/xxh3 is the common case; the repository carries anunsafe-free copy of it that computes the same hashes, for areplace github.com/zeebo/xxh3 => <go2cs clone>/src/forks/github.com/zeebo/xxh3@v1.1.0. The general fix is planned.- One bad dependency blocks everything above it. A package that fails to convert, or that the
converter refuses, is reported and skipped: the rest of the module still converts, and every project
that imports it fails to build. The run ends with exit 1, and its summary names each such package
and, for a refused one, each converted package that imports it.
-recurse=moduleconverts only your packages.
What “validated” means, and what it doesn’t
A package’s own Go Test functions were converted, run, and compared with go test verdict for
verdict, by full test name. That’s a real bar, and narrower than the word sounds:
- Tests only. Examples, benchmarks and fuzz targets never run. No race detector either.
- Matched is not passed. A test that skips on both sides counts as a match and measures nothing.
- Disclosed differences are real differences. Where a Go test asserts something a managed runtime can’t satisfy, or doesn’t yet, its exact failure is pinned and listed on the package’s proof page, linked from Validated Test Packages (Disclosures explains the kinds). Read the list for a package you lean on.
- Nothing about your dependencies.
go2cs -tests -recursetests the packages of the module you point it at, never its dependencies, so run it on each dependency you lean on.
Platforms and toolchain
- Go’s security fixes arrive with go2cs releases. The converted standard library is a conversion of
the Go release in Requirements. A fix Go issues later reaches you when go2cs
converts and publishes that patch. A project converted with
-recurse=nugettakes it on its next restore, because itsGoStdLibVersionis the Go minor with a float, such as1.26.*(Roadmap). - One Go release, one .NET release. Convert with the Go release in
Requirements, which the go2cs dotnet tool downloads for you; building the
converter from a clone needs Go 1.26.11 or later (the release
src/go2cs/go.modnames).go2cs -versionshould show that one release throughout. Rebuild after every pull. Each GitHub release carries the converter prebuilt for six platforms, with Authenticode-signed Windows executables and a GPG-signedSHA256SUMS(SHA256SUMS.asc, by the key that signs the release tag). Converted projects and thego.*packages targetnet10.0. - Where it runs. The standard library is validated on x64 Windows, on Linux, x64 and arm64 (glibc, on
Microsoft’s build of .NET: Ubuntu’s own package has an entry in Known issues), and on macOS,
Intel and Apple silicon. The roster shows each package’s counts on each platform; two
Windows-only packages have no Linux or macOS reading. The packages ship
win-x64,linux-x64,linux-arm64,osx-x64andosx-arm64; a build for any other platform is refused or warned about (Known issues). - One conversion, one operating system. Go picks build-tagged files at conversion time, so convert
once per OS (
-platforms linux/amd64), into separate output folders.
Reading and debugging the output
- You debug the C#. Breakpoints, stepping and compiler errors are on the generated
.cs. A Go panic’s own traceback does name the Go file and line, read from the program’s.pdbfiles: a publish with-p:DebugType=nonekeeps the frames and loses every file and line. - Some of the letters aren’t on your keyboard.
ж<T>,Ꮡx,goǃ(...),ᐸꟷ(ch): several look like punctuation and are letters, so an ASCII search finds nothing. Keep the glyph table open. - Don’t hand-edit converted files, the
.csprojincluded. The next conversion rewrites them, so pass build settings with-p:. For code, fix the Go, keep your own C# in a separate file, or mark a whole file[module: go.GoManualConversion](how) and merge later Go changes yourself. A renamed Go file leaves its old.csbehind, still compiled. - Start with
go2cs -recurse=nuget <module> <out>, the one form whose output restores and builds with nothing staged. Go comments are dropped unless you pass-comments. - Calling converted Go from your own C#? See Rough edges. The road runs one way: Go source can’t call a .NET API.
What you might expect to break, and doesn’t
The language itself (generics, closures, struct embedding, range-over-func, typed nil pointers in
interfaces, randomized map order), defer/panic/recover, channels and select, reflect
(encoding/json and text/template pass their own suites on it, on Windows, Linux and macOS), and net/http with HTTP/2 and
crypto/tls over real sockets.
When you hit a seam
- Start from a clean Go build:
GOTOOLCHAIN=local, thengo build ./...for the same OS and tags. - Read the conversion’s warnings and its summary line, not the exit code.
- A clean build that throws
NotImplementedExceptionwants a pure-Go build tag. A C# compile error in converted code is a converter bug until proven otherwise. - A behavior difference in the standard library? Check the package’s disclosures on Validated Test Packages.
- Check Known issues, then
open an issue with the output of
go2cs -version, your OS, the error text, and the smallest Go that reproduces it.
If you find a seam that isn’t on this page, that’s the one I most want to hear about.