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.
This page describes go2cs 1.26.11.2, the current release. Where an earlier release differs, it says so.
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: calls of C functions a shared library defines, calls of the package’s own C, C globals, and callbacks C makes into Go through a function pointer, each within limits (cgo). In go2cs 1.26.11.1, only calls of C functions a shared library defines. - Assembly,
//go:linknameand deepunsafetricks compile clean, then fail at run time. Many libraries ship a pure-Go fallback behind a build tag. A plain-recurseapplies the common ones (safe,purego,noasm) for you; an explicit-tagsreplaces them, so restate them beside your own. - By default, each live goroutine holds an operating-system thread. Thousands alive at once are fine; Go’s million are out of reach. A program built and run with async twins parks goroutines that wait in twinned code instead (experimental).
- 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
- The parts of cgo go2cs does not bind yet, such as unions, a package’s own C++, Objective-C or Fortran files, and a callback on a thread C made. In go2cs 1.26.11.1, that is everything 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 conversion names each one (warning GO2CS2012, diagnostic codes), 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. - A few generics forms.
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. A generic function whose method-set constraint go2cs meets through a shape witness stops the run witherror GO2CS2013at a site the witness cannot reach yet: a type argument or constraint from another package, a method value taken through the type parameter (f := x.M), or a value of the type parameter converted to a non-empty interface. Each site is named; calling the method instead of taking its value, or converting a concrete value, gets past it. - An identifier spelled like a name go2cs generates. A package that declares a name with a letter go2cs writes into
generated names (
Ꮡ,ᴛ,жand others), or aΔname equal to one go2cs generates in that package, stops the run witherror GO2CS2015, naming the identifier. Rename it. - Another package’s unexported interface method, met through an embedded struct. Converting
type U struct{ lib.T }tolib.I, whereIdeclares an unexportedm(), stops the run witherror GO2CS2016whenUdeclares anmof its own ormreturns a value (known issue). - 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
- Where Go leaves the order open, go2cs can read a value at a different moment than gc does. Go orders a
statement’s calls, but not a plain read of a variable against them. In a few such statements gc reads the variable
before a later call writes it, and go2cs reads it after: a map key built from a struct field beside a method call
that changes the field (
m[key{s.g, "a"}] + s.poke()), a local struct passed to ananyparameter beside a closure call that changes it (fmt.Println(s, set())), and a map key a closure captures and changes (m[k] + setK()). Both results are valid Go. Code that depends on one of them depends on the compiler, so read the value into a variable before the call. - 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). Async twins, experimental and opt-in, run goroutines that wait in twinned code on a small pool of threads. - Some deadlocks hang. A converted program prints Go’s
all goroutines are asleep - deadlock!, a header for each goroutine, and exits 2 when every goroutine,mainincluded, waits on a channel, aselect, async.WaitGroup, async.Condor async.RWMutex, and no timer is pending. The report comes about a second after the last goroutine blocks, where Go’s is immediate. It differs from Go’s in these ways:- Only a goroutine waiting on a nil channel or an empty
select {}prints its frames. Every other goroutine prints[stack unavailable: ...]under its header. - A deadlock that involves a
sync.Mutex, or async.RWMutexwriter waiting behind another writer, hangs: golib cannot tell when a goroutine waiting for a mutex has been woken. - Detection is off under
GO2CS_DEADLOCK=0, in a program that uses cgo, under the M:N scheduler (GO2CS_MN=1), in a converted test host, and in C# code that calls converted packages. A deadlock there hangs. - A thread your own C# code starts is not a goroutine. If such a thread sends on a channel or closes one, it should not be the only thing a program’s goroutines are waiting for: before its first send, the program can be reported as deadlocked. After it, detection is off for the rest of the process.
To find a deadlock that hangs, break in with a debugger. By default, each goroutine is a thread named
goroutine-N. - Only a goroutine waiting on a nil channel or an empty
- Stacks don’t grow. By default,
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. With the scheduler of async twins on, every pool thread reserves 1 GiB, or the goroutine reserve when that is larger, somain’s twin and every goroutine the scheduler runs keep at leastmain’s 1 GiB. A setGO2CS_GOROUTINE_STACKsizes the pool threads instead, lower or higher, never below 1 MiB, and then boundsmain’s recursion too; goroutines on threads of their own keep 256 MB (16 MB bounded). 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.-
A func variable takes a pointer word stored into it only when the word is another func value’s word.
*(*unsafe.Pointer)(unsafe.Pointer(&f)) = pcopies the func whenpwas read the same way from another func, and nil is the nil func. A hand-builtfuncvalwhose word is a code address panics by name: go2cs does not bind a function to a code address (func words). A callback from C into Go needs no such binding: C calls an//exportthrough its native entry point, never through a Go func value. This is go2cs 1.26.11.2. In go2cs 1.26.11.1 such a store is lost with no message: the func variable keeps the value it had, so a func that was nil stays nil and a call through it panics. - A func value’s word does not keep a closure alive. Held as an
unsafe.Pointeror auintptr, the word of a closure names it only while something else holds the closure. Once nothing does and a collection runs, storing the word back into a func variable, or calling through it, panics by name (“names no live func”). In Go, theunsafe.Pointerkeeps the closure alive. A top-level function’s word is good for the life of the process. - 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 setZONEINFOorGOROOT(why). - A few quiet ones, each rare, where converted code gives a different answer and says nothing:
cap()after appending to a slice that does not escape can differ from Go’s when-stack-appendis off, as it is by default for a plain or-recurseconversion (known issue).- In a few statement forms, a variable read beside a call sees its value from before the call, where Go’s compiler reads it after (known issue). Both orders are allowed by the Go specification.
- A main package converted on its own, without
-recurse, does not carry its module’s defaultGODEBUGsettings, which Go derives from thegoline. Ago 1.22module’s program then runs with today’s defaults: its timers use Go 1.23’s unbuffered channels, for example, socap(t.C)reads 0, and aStopafter the timer fired reportstruewhere Go reportsfalseand leaves the value in the channel. Convert with-recurse, or setGODEBUGin the environment, which is honored. - 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”. Measured - A write through
unsafe.StringData’s pointer into a string literal or a one-byte string faults in Go, because those bytes are read-only. In go2cs those bytes are shared by every equal string, so the write changes every later evaluation of that literal, in every package, or every one-byte string of that byte. SetGO2CS_CHECK_STRING_WRITES=1(Tuning) to have it caught by name:unsafe.StringDatathen gives the pointer a private copy of the bytes, so the write reaches no other string, and the program panics at the next read through that pointer (*p, or a pointerunsafe.Addmade from it) or at the nextunsafe.StringDataover the same string. A write through a view that reads the bytes directly, a slice fromunsafe.Slice(p, n)or a(*[N]byte)(unsafe.Pointer(p))array pointer, also lands in the copy, and is reported only if a later access goes through one of those two checks. TheDataof areflect.StringHeaderlaid over such a string names the same copy. With the check on, three cases are still not covered, and none of them panics:- A literal hoisted into a
static readonlyfield ("..."u8), which the standard library does throughout and a package converted with-hoist-literalsdoes too. A write throughunsafe.StringDatachanges that literal wherever it is used: after a write through the pointer toerr.(*strconv.NumError).Funcfromstrconv.ParseBool("x"), every later such error names the changed function. - A literal written in place as
"..."u8(format strings and other string arguments in converted code). It becomes a new array at each evaluation, so a write throughunsafe.StringDatais private to that one value. - A string
unsafe.Stringbuilds fromunsafe.StringData’s pointer. It shares the private copy, so it reads any byte later written there, andunsafe.StringDataover it hands out a pointer with no check.
A heap string (one built at run time) behaves as in Go: the write changes it and every string sharing its bytes.
- A literal hoisted into a
- 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. - On Arm64, and on x64 built with
GOAMD64=v3, Go may computex*y + zas one fused multiply-add, rounded once, which the Go specification allows. Converted code multiplies and adds as two steps, rounded twice, on every platform. So a float result can differ by the rounding of the product, and an add that cancels can make that the whole result. Converted code equals the default x64 Go build: forfunc mulAdd(x, y, z float64) float64 { return x*y + z },mulAdd(0.1, 10, -1)is0in converted code and from the default x64 build, and5.551115123125783e-17when Go fuses it. Writemath.FMA(x, y, z)where the fused result matters: it is fused on every platform, in Go and in converted code. <!– 2026-12-01 (P6, COORD 20261130T235840Z, from P3’s FOUND B in inbox/COORD 20261130T232837Z-P3.md; the GOAMD64=v3 arm, the size and the rewrap are P3’s read 20261201T001144Z, folded per COORD 20261201T002830Z). MEASURED on linux/amd64 with go1.26.11, mulAdd marked //go:noinline:GOARCH=arm64 go build -gcflags=-SholdsFMADDD F0, F2, F1, F0;GOAMD64=v3 go build -gcflags=-SholdsVFMADD231SD, and that binary prints 5.551115123125783e-17;- the default x64 build prints 0;
- the conversion (master 4e3850f0b8), built and run on linux/amd64, prints 0;
- math.FMA(0.1, 10, -1) prints 5.551115123125783e-17 from the default x64 build, from the v3 build and from
the conversion.
READ, not measured: the Arm64 Go binary’s output and the converted program on Arm64 (no Arm64 host ran them;
RyuJIT does not contract a separate multiply and add into one instruction). Go’s runtime complex128div has
the same shape at
real(m) + ratio*imag(m). –>
- In a cgo package, a pointer into Go memory rebuilt from a number can reach C unchecked in three narrow cases (cgo).
- On Windows x64, a system call to an address Control Flow Guard does not list as a call target ends the
process. Converted programs run with Control Flow Guard under the JIT, as measured on the apphost and on
dotnet.exe(and under Native AOT when built with<ControlFlowGuard>Guard</ControlFlowGuard>), andsyscall’s call trampoline checks the function it is given the way the process’s own indirect calls are checked. An exported function, or a pointer the API handed out, passes. An address computed by offset inside a system DLL, which Go and an unguarded call would reach, ends the process with0xc0000409and no go2cs message. Call exported functions, throughLazyProcorGetProcAddress. The trampoline makes one more check with the same exit code: its argument block must lie on the calling thread’s live stack, which everyProc.CallandSyscallNmeets, so a process that ends with0xc0000409at a system call was stopped by one of the two. - Under Native AOT on Windows,
syscall.NewCallbackrefuses a func whose type no call site names: one that reaches it only as ananyvalue (one stored in an interface before the call, as the runtime’s own callback tests do), one whose func type names a type parameter, and, from hand-written C#, a variadic or optional-parameter method, one with arefparameter or more than 16 parameters, or one with a pointer, ref-like or file-local type in its signature. The call panics with “no native code for callback type”. Pass the func itself, of its own func type. - On Windows,
syscall.NewCallbacktakes a func of 0 to 16 arguments. Go takes any number whose argument frame fits 64 words. A func of 17 or more panics with “N-argument callbacks are not implemented in this port”; under Native AOT it panics with “no native code for callback type” instead, since a func of that many arguments has no type a call site can name.
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 one go2cs binds. In go2cs 1.26.11.1, that 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.
Since 1.26.11.2, a package also converts when it calls C that its preamble or its own C or assembly files define
(go2cs compiles those into a side library beside the bindings), or passes a void * that points into Go memory holding
no Go pointers (held still for the call). It reads and writes a C variable of a scalar or struct type in place, and C
can call back into an //export through a function pointer Go handed it. A struct with a void * member converts by
pointer, the member nil or C memory, and a C pointer typedef (typedef const char *T) converts as a result and as a
parameter.
Since 1.26.11.2, Go code that walks C memory converts too: it reads and writes a pointer field of a C struct
that lives in C memory (l.next), and loads and stores through a **C.T (*p, as a walk down a C list such as
addrinfo’s ai_next does). A pointer field reached through a nested struct value, an array of pointers, a field
whose type is a C pointer typedef, and a union are still refused by name, and so is storing a pointer into Go memory
into C memory. In go2cs 1.26.11.1, reading a pointer field of a C struct in C memory fails with a panic.
Since 1.26.11.2, a slice of C memory whose element is a C struct with a pointer field (from unsafe.Slice, or
(*[N]C.T)(p)[:]) converts as in Go: an element’s fields are read and written through the index, a pointer field
included, an element read by value is a copy decoded out of C memory, and a slice of an array member is a window on
the C bytes. Storing a whole element by value (s[i] = v, or a range statement that assigns s[i]), storing into an
element of an array member (s[i].a[j] = x), and copy into, clear of or an append within the capacity of such
a slice are refused by name. Through a pointer to an element (p := &s[i]) the fields and the whole element read as
through the index, but an element of an array member (p.a[j]) is refused by name: read it as s[i].a[j].
Handing such a pointer to a function that reads through it (f(p) with a *C.T parameter) and reading a field
through a written dereference ((*p).f) are refused by name: read the element as *p or the field as p.f where
the pointer is.
A slice of an array member of a nested struct (s[i].in.a[:]) is refused by name.
Since 1.26.11.2, a number made from a Go pointer (unsafe.Pointer(uintptr(unsafe.Pointer(&x)) + off), in one
expression or through a variable) is handed to C as a void * when it points into Go memory that holds no Go pointers,
and that memory is held still for the call. A number one past the end of that memory, the end of a begin/end pair, is
not held still, so C may only compare it, never read or write through it. A 64-bit integer argument that is go2cs’s
stand-in for the address of a Go value holding Go pointers is refused by name.
Since 1.26.11.2, C may keep a Go pointer past the call when a runtime.Pinner pins the memory, as cgo requires:
the pin holds the value and every array inside it still until Unpin. A pinned value whose Go layout is not its C
layout (a struct holding an array, for instance) is refused by name. Two cases are not covered:
- A pointer C keeps without a Pinner is invalid Go, though it usually works under Go, whose heap does not move. Here the memory can move at the next collection, and nothing reports it.
- Pinning an element of an array does not pin the struct that holds the array (Go’s pin does). Pin the whole value.
One target. A -cgo conversion is for one operating system and architecture: the machine’s own, or another one
named with -platforms when CC names that target’s C compiler (for example zig cc -target <triple>). The converted
package refuses its C bindings on any other: when the package loads, before any of its code runs. A single-package
conversion builds against a go2cs clone (dotnet build -p:go2csPath=<go2cs>/src/). Under -recurse -cgo a module’s
cgo packages convert with the module, and under -recurse=nuget -cgo they reference the go.* packages. A module
with a cgo package packs for publishing as a package for each of win-x64, linux-x64, osx-x64, linux-arm64
and osx-arm64, each with its own C binding. Such a package is
published only against a go.lib that carries the load-time target check, which the go.* 1.26.11.1 packages do not.
The standard library itself is converted with CGO_ENABLED=0, and a module converted with -recurse -cgo uses it as
it is. So a package that imports net or os/user gets their builds without cgo, the ones Go itself uses with
CGO_ENABLED=0: net resolves host names with Go’s own resolver, not the C library’s, and os/user reads the user
database files directly. go2cs does not convert the net resolver with cgo yet (Roadmap). A
package that imports runtime/cgo or plugin is refused by name: without cgo they are not working builds.
That is go2cs 1.26.11.2. go2cs 1.26.11.1 converts one cgo package at a time, for the machine’s own operating system
and architecture only: there -cgo does not combine with -recurse, a cgo package cannot be packed, and the target
check runs at the package’s first C call rather than when it loads.
What is refused, by name. Each of these is not supported yet; the Roadmap says what is planned.
- a pointer into Go memory handed to C as a
void *, or toC.GoBytes,C.GoStringorC.GoStringN, when that memory holds Go pointers (cgo’s own rule) or go2cs cannot hold its storage still; the message 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
#definethat is not a constant. A function or variable the preamble defines, or a C or assembly file of the package’s own defines, is compiled into a side library beside the bindings, except in a package that names#cgo pkg-config. A name a C++, Objective-C, Fortran or.sysofile of the package’s own could define is refused by name, and so is a name two of the package’s files define as a global symbol, which C’s link and Go’s both reject. A name the package’s own C calls that nothing in the package defines and no library it links exports (another package’s C, or a Go//exportcalled by its C name) is refused by name when the side library is linked, on every target: Go links all of a program’s C together, and go2cs links each package’s C alone. So is a name in a library the package does not name in#cgo LDFLAGS(a preamble callingsinwith no-lm), which go’s link refuses too. A file of the package’s own that nothing the package’s Go uses needs is left out of the conversion, and named (warning GO2CS2017): a constructor in it runs under go and not here; - an
//exportC calls on a thread no goroutine called C from (a thread the C library made), which ends the program by name; an export C calls by its name rather than through a function pointer Go handed it; and an export that is a method, returns more than one result or a result that is not a C scalar, or takes a parameter that is not a C scalar, avoid *, a pointer to a C type, or a pointer to a pointer to a C struct (C’s array of struct pointers, read through its address, an array view over it as go-sqlite3 readsargv, or a direct*argv). A pointer to a pointer to a C scalar,char **argvamong them, is refused. An export C calls back through a pointer, on the thread of the Go call into C, runs as Go runs it. A panic in it reaches the Go code that called C, as it does under go, andrecover()there stops it; but C gets the result’s zero value and runs on to the end of its call, where under go the C frames between are abandoned. A further callback during that C call returns zero without running Go code, and the panic arrives only when the C call returns: a C call that never returns (a loop that keeps calling back) never delivers it, where go ends the program or unwinds at the panic; - a C variable whose type is not a C scalar or struct (an array, a pointer, a function pointer or a union);
C.xof a scalar or struct type reads and writes the variable in place, as Go does, once a library the package links exports it; - a C function used as a value, unless it is an
//export(its address is then the export’s native entry point), andgo C.f(…)with a pointer cmd/cgo checks; - 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, .... 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. For a pointer to one whole Go struct or scalar, in a variable or a struct field, go2cs
hands C a copy of the value it points at, and copies it back after the call. A pointer to a scalar element of a Go
array or slice, a typed scalar view over Go storage, and memory pinned with runtime.Pinner cross in place instead,
held still for the call (an element of a Go array of C structs is copied with its whole array, as below). So cgo’s
pointer check differs from Go’s in five cases, all where a program breaks or bends cgo’s pointer rules. In two, Go
panics and go2cs proceeds:
- a pointer held in a variable, when the object it points into also holds a Go pointer;
- a pointer held in a variable, when the object it points into lives in package-level memory.
Go checks a pointer held in a variable against the whole object it points into. go2cs proceeds in both cases, since C only sees the copy (or, for a scalar element of a Go array, the array’s own memory, which holds no Go pointer). This variable check is the one most cgo calls in the Go toolchain’s own cgo packages take.
In three, Go proceeds and go2cs refuses the call when it is made:
- a struct member that points at memory pinned with
runtime.Pinner; - any pointer under
GODEBUG=cgocheck=0; - a struct passed by value whose pointer member points into Go memory that holds no pointer.
A Go struct viewed as a C struct crosses as an image, and C’s writes land when the call returns. A struct
pointer that views a Go struct of another type which holds an array (net’s
(*C.struct_sockaddr)(unsafe.Pointer(&sa)), sa a syscall.RawSockaddrInet4) has no storage go2cs can hand C, so
go2cs hands C an image of the whole Go struct, at Go’s own offsets, and decodes it back after the call. It decodes
only when C changed the image, so C’s write lands in the Go struct when the call returns, not while C runs:
- a goroutine that reads the struct during a blocking call sees the old value;
- if C and a goroutine both write it during the call, C’s write wins at the return;
- a
boolC writes as a byte other than 0 or 1 reads back astrue.
Three views of one Go value in one call share one image, as Go’s one memory does. One Go value handed to C both as such a view and through another pointer of the same call is refused by name, and so is a view of a Go struct that holds a Go pointer.
A known memory-safety gap: a pointer rebuilt from a number, in three narrow cases. A number made from a Go
pointer (u := uintptr(unsafe.Pointer(p)), then unsafe.Pointer(u + n), or Go’s one-expression form) and handed to
C as a void * crosses, since 1.26.11.2, as that Go memory, held still for the call, while go2cs can tell which
Go value it came from. In go2cs 1.26.11.1 such a number is refused by name. In both, three cases cross as C memory
instead, 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.
A Go pointer in a void * member of one struct is refused with Go’s text for the call’s form. For C.f(&x) Go
names the member’s kind, “Go pointer to unpinned Go unsafe pointer”; through a variable holding the struct’s address
(p := &x; C.f(p)) Go checks the whole object and says “Go pointer to unpinned Go pointer”. go2cs says the same in
each, from the call form the conversion passes the wrapper.
A Go array of C pointers costs its whole length on every call. C.f(&argv[0]) lets C read or fill every
pointer in the array, as in Go. go2cs holds such an array as Go pointers rather than as machine words, so for the
call it copies every element of the array into a word array, hands C that, and copies every word C changed back
afterwards. The copy covers the whole array behind the slice, not only the part C uses: argv[2:] of a long array
copies the long array, on every call. A word C writes that points into the Go memory the call handed it, the array
itself included (argv[0] = &argv[2]), is refused by name, where Go would keep it. An array of C pointers that
lives in C memory crosses by its own address, with no copy.
A Go array or slice of C structs costs its whole length on every call. C.f(&cols[0]) lets C read or write
every struct in the array, before the one it is handed included, as in Go. go2cs holds such structs in a layout C
cannot read, so for the call it copies every element of the backing array into an array of C structs, hands C the
element’s copy, and after the call copies back each element whose bytes C changed. So a goroutine’s write to an
element C did not touch survives the call. The copy covers the whole backing array, from its first element, whatever
part C uses. Where go2cs differs from Go:
- C’s writes land in the Go array when the call returns, not while C runs;
- two pointers into one Go array in one call (
swap(&a[i], &a[j])), or one such pointer beside another pointer to the same array, are refused by name, where Go hands C the one array; - a pointer C returns, or writes into a struct, that points inside an element (not at an element’s start), or one past the array’s end, is refused by name, and so is a pointer member C sets to another element;
- for an element before the slice Go checks (
&s[0]wheresiscols[1:]), or past its capacity (cols[0:2:2]), a Go pointer in a pointer member crosses as NULL, and a NULL C stores there is not seen; Go checks nothing there either; - a C function used as a value (
defer C.f(&s[0]),go C.f(…),f := C.f) is checked as the address form, from the first element of the backing array, where Go checks the slice the call names; - for
p := &x.cols[0]; C.f(p), Go checks the whole object that holds the array, and for a package-level variable holding Go pointers it panics; go2cs checks the array itself. An element of an array in C memory crosses by its own address, with no copy.
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, or rolls forward to a newer one when no .NET 10 runtime is installed, 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. A Native AOT publish adds two more codes: one IL3053 for each package with AOT analysis warnings (todayruntime,internal.abiandreflect), and one IL3000, whereruntimereadsAssembly.Locationto open a symbol file; the path is empty in a native image, andruntimefalls back to reading the file another way. - 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, and the conversion names each stub it leaves (warning GO2CS2012). Where the same package already holds the answer in Go under another name, go2cs forwards the stub to it: zeebo/xxh3’saccumNEONandaccumBlockNEON, which its arm64 build calls for every input over 240 bytes, are forwarded to its ownaccumScalarandaccumBlockScalar, so plain xxh3 builds and hashes as Go does on arm64 too (below). 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. With the tag on, testify works: on the master branch, github.com/stretchr/objx’s suite, which uses testify, validates (validated modules). - 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. -
github.com/zeebo/xxh3 converts as is, including the two things that used to stop it: its
unsafeheader views and, on arm64, its NEON assembly. The views of a string’s or a slice’s bytes run as Go’s do: a string or a[]byteread through its header,*(*struct{ p unsafe.Pointer; n uint })(unsafe.Pointer(&s)), then bytes read or written atunsafe.Pointer(uintptr(p) + i)or through(*[8]byte)(p). It computes the same hashes as Go on windows/amd64, linux/amd64, linux/arm64 and macOS on Intel and Apple silicon, with noreplace. The repository’s copy of xxh3 atsrc/forks/github.com/zeebo/xxh3@v1.1.0, which has nounsafeviews, is no longer needed for it. - A store through a
[]byteread as a string panics, or is lost.*(*string)(unsafe.Pointer(&b)) = s, and the same store through a two-word string header (*(*struct{ p unsafe.Pointer; n uint })(unsafe.Pointer(&b)) = h), replaces the slice’s data pointer and length in Go and keeps its capacity. The views go2cs reads these through are read-only. When the conversion is written in the assignment itself, as above, the converted statement panics withgo2cs: store through a read-only view; in aforstatement’s init or post clause, the converter stops on the file and names it (GO2CS2008). When the view is held in a variable first (p := (*string)(unsafe.Pointer(&b)); *p = s), or passed to a function that stores through it, the store goes into the view, which panics by name on the next access throughp. If there is none, the store is lost with no word:len(b)still reads the old length. - 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.
- The first pass runs untiered.
go2cs -testsruns the converted tests with .NET’s tiered compilation off, so each method is fully compiled the first time it runs. A test that times a few tens of milliseconds across code it has not called before can fail where Go passes. Pass-test-tieredto run such a test as a .NET program normally runs. - 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, built for .NET 10. 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; on a machine with no .NET 10 runtime a converted program runs on a newer one, which the packages are not validated on (FAQ). - 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; the
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.