La valeur derrière l'interface The value behind the interface

Une interface, c'est une paire (type, valeur). L'assertion x.(T) et le type switch la rouvrent ; le boxing et l'indirection la paient. Quand any sauve la mise, et quand il faut s'en passer. An interface is a (type, value) pair. The x.(T) assertion and the type switch reopen it; boxing and indirection pay for it. When any saves the day, and when to do without it.

Audience
Dev qui manipule des any et des type switch et veut en connaître le coût et les alternatives Dev handling any and type switches who wants to know their cost and alternatives
ChapitresChapters
5
LectureReading
≈ 17 min
NiveauLevel
●●●○
Date
Fév 2027 Feb 2027

InterfacesType assertionCoût

SommaireContents ·
№ 01CadrageFraming3 min

L'interface a emballé une valeur. L'assertion la rouvre.The interface wrapped a value. The assertion reopens it.

Deux numéros durant, la paire (type, valeur) nous a servis ou trahis sans qu'on y touche. On va maintenant l'ouvrir nous-mêmes. L'assertion de type, x.(T), prend une interface et en extrait le type concret qu'elle transporte — elle fait le chemin inverse de l'emballage. Le hic, c'est qu'on affirme un type : si l'interface n'en contient pas, l'assertion nue panique. D'où la forme à deux retours, v, ok := x.(T), qui ne panique jamais : elle pose une question au lieu d'asséner une certitude. C'est la version sûre, et la seule qu'on devrait écrire par défaut.For two issues, the (type, value) pair served or betrayed us without our touching it. Now we'll open it ourselves. The type assertion, x.(T), takes an interface and extracts the concrete type it carries — it walks the wrapping backwards. The catch is that you assert a type: if the interface holds another, the bare assertion panics. Hence the two-result form, v, ok := x.(T), which never panics: it asks a question instead of stating a certainty. It's the safe version, and the only one you should write by default.

L'assertion nue : aie raison, ou paniqueThe bare assertion: be right, or panic
var i any = "hello"           // la paire : (string, "hello")

s := i.(string)               // "hello" — on ressort le type concret
n := i.(int)                  // panic: interface conversion:
                              //        string is not int
// l'assertion nue exige d'avoir RAISON sur le type — sinon, panic.
La forme à deux retours : une question, pas un pariThe two-result form: a question, not a bet
s, ok := i.(string)           // "hello", true
n, ok := i.(int)              // 0, false  — pas de panic, ok dit l'échec
if ok {
    use(n)                    // on n'entre QUE si le type colle
}
// la forme à deux retours transforme une erreur fatale en branche.
Emballer, puis rouvrirWrap, then reopen
42
int concret
i = x
↓
boxing
(int, 42)
any
i.(int)
↓
assertion
42
int concret

Ranger un int dans une any remplit la paire ; l'assertion i.(int) la vide à nouveau dans un int concret. L'assertion n'est pas une conversion — elle ne transforme rien : elle vérifie que le type rangé est bien celui qu'on demande, et rend la valeur telle quelle.Storing an int in an any fills the pair; the assertion i.(int) empties it back into a concrete int. The assertion isn't a conversion — it transforms nothing: it checks the stored type is the one you ask for, and returns the value as is.

Le réflexe du numéroThe issue's reflex

« Une interface, on ne la rouvre qu'avec le ok. » L'assertion nue est un pari sur le type ; perdu, il panique. La forme à deux retours en fait une branche. Tout le numéro déroule ce qu'on peut faire de la paire rouverte — router selon le type, en payer le coût — et quand il vaut mieux ne jamais l'avoir emballée."You reopen an interface only with the ok." The bare assertion is a bet on the type; lost, it panics. The two-result form turns it into a branch. The whole issue unrolls what you can do with the reopened pair — route on type, pay its cost — and when you'd have been better off never wrapping it.

Asserter une interface, pas qu'un type concret.Asserting to an interface, not only a concrete type.

T dans x.(T) n'est pas forcément un type concret : ça peut être une autre interface. x.(io.Reader) demande « la valeur cachée sait-elle Read ? » et, si oui, te rend une vue io.Reader dessus. C'est le mécanisme derrière des idiomes comme err.(interface{ Temporary() bool }) : on teste à l'exécution si la valeur satisfait un comportement, sans connaître son type. La paire ne rend pas que du concret — elle rend l'angle de vue qu'on lui demande, du moment qu'il est compatible.T in x.(T) needn't be a concrete type: it can be another interface. x.(io.Reader) asks 'does the hidden value know how to Read?' and, if so, hands you an io.Reader view of it. It's the mechanism behind idioms like err.(interface{ Temporary() bool }): you test at runtime whether the value satisfies a behaviour, without knowing its type. The pair returns not only concretes — it returns the angle you ask for, as long as it's compatible.

№ 02La surpriseThe surprise4 min

Quand il y a plusieurs types possibles, on n'enchaîne pas les assertions. On switch.When several types are possible, you don't chain assertions. You switch.

L'assertion à deux retours règle un type à la fois. Dès qu'on doit router selon plusieurs types possibles — décoder un any venu d'un JSON, traiter une valeur dont la forme varie — l'enchaînement de if devient lourd et fragile. Go a une construction faite pour ça : le type switch, switch v := x.(type). Il ouvre la paire une fois et branche selon le type concret qu'elle contient, en liant au passage une variable déjà du bon type dans chaque cas. C'est l'assertion élevée au rang d'aiguillage — plus lisible, et impossible d'oublier un ok.The two-result assertion handles one type at a time. The moment you must route on several possible types — decoding an any from JSON, handling a value whose shape varies — the if-chain turns heavy and brittle. Go has a construct made for it: the type switch, switch v := x.(type). It opens the pair once and branches on the concrete type it holds, binding along the way a variable already of the right type in each case. It's the assertion raised to a switchboard — more readable, and impossible to forget an ok.

Une branche par type, et autant de ok à écrireOne branch per type, and as many oks to write
// router selon le type, à la main : une cascade de if-assertions
if s, ok := x.(string); ok {
    handleString(s)
} else if n, ok := x.(int); ok {
    handleInt(n)
} else if f, ok := x.(float64); ok {
    handleFloat(f)
} else {
    handleUnknown(x)
}
// répétitif, et chaque branche re-déclare son propre ok.

La cascade fonctionne, mais elle se répète : chaque branche redéclare son ok, l'ordre devient significatif sans que rien ne le signale, et ajouter un type oblige à recopier le motif. Surtout, l'intention — « router selon le type » — est noyée dans la mécanique du if … ; ok. Quand on voit trois assertions enchaînées sur la même variable, c'est le signe qu'un type switch attend.The chain works, but it repeats itself: each branch redeclares its ok, order becomes significant with nothing flagging it, and adding a type means copying the pattern again. Above all, the intent — 'route on type' — drowns in the mechanics of if … ; ok. When you see three assertions chained on the same variable, it's the sign a type switch is waiting.

Asserter un comportement, pas qu'un typeSwitching on behaviour, not only type

Les cas d'un type switch peuvent être des interfaces. case fmt.Stringer: attrape tout ce qui sait String(), quel que soit son type concret. C'est exactement ce que fait la bibliothèque standard pour formater : fmt teste si la valeur est une Stringer, une error, et appelle la bonne méthode. Le type switch devient alors un aiguillage par capacité — non « quel type es-tu ? » mais « que sais-tu faire ? ». L'ordre des cas compte ici : le premier compatible gagne.A type switch's cases can be interfaces. case fmt.Stringer: catches anything that knows String(), whatever its concrete type. It's exactly what the standard library does to format: fmt tests whether the value is a Stringer, an error, and calls the right method. The type switch becomes a switchboard by capability — not 'what type are you?' but 'what can you do?'. Case order matters here: the first compatible one wins.

Un type switch est un aveu.A type switch is a confession.

Pratique, mais à surveiller : router selon le type concret, c'est souvent renoncer au polymorphisme que l'interface offrait gratuitement. Si tu fais un type switch pour appeler Area() différemment selon Cercle ou Carré, c'est qu'une méthode Area() sur une interface Shape aurait mieux fait le travail — sans switch, sans cas oublié. Le type switch est légitime aux frontières (décodage, valeurs vraiment hétérogènes) ; au cœur du domaine, il trahit souvent une interface qu'on aurait dû définir. On y revient au dernier chapitre.Handy, but watch it: routing on concrete type often means giving up the polymorphism the interface offered for free. If you type-switch to call Area() differently for Circle or Square, an Area() method on a Shape interface would have done it better — no switch, no forgotten case. The type switch is legitimate at boundaries (decoding, genuinely heterogeneous values); at the heart of a domain, it often betrays an interface you should have defined. More on this in the last chapter.

L'assertion demande « es-tu ce type ? ». Le type switch demande « lequel es-tu ? » — et répond dans la foulée.The assertion asks "are you this type?" The type switch asks "which one are you?" — and answers in the same breath.
№ 03La mécaniqueThe mechanics5 min

Emballer une valeur dans une interface n'est pas gratuit. Ça alloue et ça indirige.Wrapping a value in an interface isn't free. It allocates and it indirects.

La souplesse de l'interface a un prix matériel, qu'on paie sans le voir. Une valeur d'interface est une paire de deux mots : un pointeur vers la description du type, un pointeur vers la donnée. Ranger un entier dans une any, c'est le « boxer » — souvent l'allouer sur le tas pour pouvoir le pointer. Et chaque appel de méthode via l'interface passe par une table d'indirection, au lieu d'un saut direct. Sur un appel isolé, c'est imperceptible. Dans une boucle chaude, ou sur des millions d'éléments, le []any qui semblait innocent multiplie les allocations et les sauts. La règle n'est pas « évite les interfaces » — c'est « sache ce qu'elles coûtent, et ne les paie pas pour rien ».The interface's flexibility has a material price, paid without seeing it. An interface value is a pair of two words: a pointer to the type's description, a pointer to the data. Storing an integer in an any 'boxes' it — often allocating it on the heap so it can be pointed at. And every method call through the interface goes through an indirection table, instead of a direct jump. On a single call, it's imperceptible. In a hot loop, or over millions of elements, the innocent-looking []any multiplies allocations and jumps. The rule isn't 'avoid interfaces' — it's 'know what they cost, and don't pay it for nothing.'

Des entiers contigus, additionnés directementContiguous integers, added directly
func sum(xs []int) int {        // valeurs concrètes, côte à côte en mémoire
    t := 0
    for _, x := range xs {
        t += x                  // addition directe, zéro indirection
    }
    return t
}
// []int est un bloc contigu d'entiers. Rien à emballer, rien à allouer.

Un []int est un bloc contigu d'entiers : le processeur les lit en cache, les additionne sans détour, n'alloue rien. C'est le cas où le concret écrase l'abstrait sur le plan brut de la performance. Tant que le type est connu à la compilation, il n'y a ni paire, ni boxing, ni table — juste la donnée et l'opération. C'est le mètre étalon auquel comparer tout ce qui passe par une interface.A []int is a contiguous block of integers: the CPU reads them from cache, adds them without detour, allocates nothing. It's the case where the concrete crushes the abstract on raw performance. As long as the type is known at compile time, there's no pair, no boxing, no table — just the data and the operation. It's the yardstick to compare anything going through an interface against.

fmt.Println, l'usine à boxing discrètefmt.Println, the quiet boxing factory

La signature de fmt.Println est (a ...any) : chaque argument que tu lui passes est emballé dans une interface, donc potentiellement alloué. C'est invisible et sans conséquence pour un log occasionnel — mais dans une boucle de hot path, un fmt.Sprintf par itération est une source d'allocations classique qu'un profil mémoire révèle aussitôt. Là où la perf compte, préfère la concaténation typée ou strconv, et garde fmt pour ce qu'il fait de mieux : la lisibilité, pas le débit. Le go test -bench -benchmem chiffre tout ça en une commande.fmt.Println's signature is (a ...any): every argument you pass is wrapped in an interface, hence potentially allocated. It's invisible and harmless for the occasional log — but in a hot-path loop, a fmt.Sprintf per iteration is a classic allocation source a memory profile reveals at once. Where performance matters, prefer typed concatenation or strconv, and keep fmt for what it does best: readability, not throughput. go test -bench -benchmem quantifies all of it in one command.

L'interface te fait gagner en généralité. Elle te le facture en allocations et en sauts — discrètement, à chaque emballage.The interface buys you generality. It bills you in allocations and jumps — quietly, on every wrap.
№ 04Le piègeThe trap4 min

La meilleure assertion est celle qu'on n'écrit pas. any n'est pas un type générique.The best assertion is the one you don't write. any is not a generic type.

On a appris à rouvrir la paire ; le dernier réflexe à acquérir, c'est de ne pas l'emballer quand on n'a pas à le faire. Pendant longtemps, écrire du code « générique » en Go passait par any : on acceptait n'importe quoi, et on assertait à la sortie. C'est souple, mais c'est repousser à l'exécution un contrôle que le compilateur aurait pu faire — chaque assertion est un panic en puissance. Depuis Go 1.18, les génériques offrent l'alternative : un type paramètre vérifié à la compilation, sans boxing ni assertion. La question n'est plus « comment asserter proprement ? » mais « ai-je vraiment besoin d'une interface ici, ou d'un paramètre de type ? ».We learned to reopen the pair; the last reflex to acquire is not to wrap it when you needn't. For a long time, writing 'generic' Go went through any: you accepted anything, and asserted on the way out. It's flexible, but it defers to runtime a check the compiler could have done — every assertion is a latent panic. Since Go 1.18, generics offer the alternative: a type parameter checked at compile time, no boxing, no assertion. The question is no longer 'how do I assert cleanly?' but 'do I actually need an interface here, or a type parameter?'

any accepte tout — et reporte l'erreur à l'exécutionany accepts everything — and defers the error to runtime
// avant les génériques : tout passe par any, et on assert à la sortie
func Max(a, b any) any {
    // comment comparer deux any ? il faut un type switch interne,
    // un cas par type ordonnable… et on retombe sur l'assertion
    ...
}
m := Max(3, 5).(int)        // assertion OBLIGATOIRE en sortie, panic possible
s := Max("a", "b").(int)    // compile très bien — panic à l'exécution

Avec any, le compilateur ne sait plus rien : Max("a", "b").(int) compile sans broncher et panique à l'exécution. Tu as troqué la sûreté de type contre de la souplesse, et tu paies à la sortie en assertions et en boxing. Chaque any dans une signature est une question repoussée : « de quel type s'agit-il vraiment ? » — à laquelle il faudra répondre plus tard, par une assertion, au pire moment, en production.With any, the compiler knows nothing anymore: Max("a", "b").(int) compiles without flinching and panics at runtime. You traded type safety for flexibility, and you pay on the way out in assertions and boxing. Every any in a signature is a deferred question: 'what type is this really?' — to be answered later, by an assertion, at the worst moment, in production.

Quand any reste le bon choixWhen any is still the right call

Les génériques ne tuent pas any ; ils le rangent à sa juste place. any reste le bon outil quand l'ensemble des types est vraiment ouvert : décoder un JSON arbitraire, formater l'inconnu dans fmt, stocker des valeurs hétérogènes sans relation commune. La frontière est nette — générique quand les types partagent une forme, any quand ils n'en partagent aucune. Le mauvais réflexe, ce n'est pas d'utiliser any, c'est de l'utiliser là où un paramètre de type aurait tout su d'avance.Generics don't kill any; they put it in its place. any stays the right tool when the set of types is genuinely open: decoding arbitrary JSON, formatting the unknown in fmt, holding heterogeneous values with no common relation. The line is clean — generic when the types share a shape, any when they share none. The bad reflex isn't using any, it's using it where a type parameter would have known everything in advance.

L'interface qui compte le plus arrive.The interface that matters most is coming.

Tout ce volume a tourné autour d'une mécanique : la satisfaction implicite, la paire, le typed nil, l'assertion, le coût. Le volume 4 prend la plus importante de toutes les interfaces — error, une interface à une méthode, Error() string — et en fait une philosophie entière. Les erreurs sont des valeurs : on les compare, on les enveloppe, on les inspecte avec exactement les outils qu'on vient de voir. errors.Is et errors.As, qu'on disséquera, ne sont rien d'autre que des assertions de type déguisées. Vol. 4 commence : les erreurs sont des valeurs.This whole volume circled one mechanism: implicit satisfaction, the pair, the typed nil, the assertion, the cost. Volume 4 takes the most important interface of all — error, a one-method interface, Error() string — and turns it into a whole philosophy. Errors are values: you compare them, wrap them, inspect them with exactly the tools we just saw. errors.Is and errors.As, which we'll dissect, are nothing but type assertions in disguise. Vol. 4 begins: errors are values.

Emballer dans any, c'est dire au compilateur « ne regarde pas ». Un paramètre de type lui dit « regarde, et arrête-moi si je me trompe ».Wrapping in any tells the compiler "don't look." A type parameter tells it "look, and stop me if I'm wrong."
№ 05Bilan & éditoWrap-up & editorial2 min

Rouvrir la paire est un pouvoir. Ne pas l'emballer en est un autre.Reopening the pair is one power. Not wrapping it is another.

Quatre points clôturent ce numéro, et le volume. L'assertion x.(T) rouvre la paire — toujours avec le ok, jamais à nu. Le type switch en fait un aiguillage quand plusieurs types sont possibles. L'emballage a un coût réel : boxing qui alloue, dispatch qui indirige, sensible dès qu'on entre en boucle. Et la meilleure abstraction est souvent celle qu'on n'emballe pas : pour des types homogènes, un paramètre générique reprend à any la sûreté et la performance qu'il avait coûtées. Sous tout cela, une seule idée : la paire (type, valeur) est un outil à manier sciemment, pas un automatisme.Four points close this issue, and the volume. The x.(T) assertion reopens the pair — always with the ok, never bare. The type switch turns it into a switchboard when several types are possible. Wrapping has a real cost: boxing that allocates, dispatch that indirects, felt the moment you enter a loop. And the best abstraction is often the one you don't wrap: for homogeneous types, a generic parameter takes back from any the safety and performance it had cost. Beneath it all, a single idea: the (type, value) pair is a tool to wield knowingly, not a reflex.

L'idéeThe ideaLa règleThe ruleSi tu la ratesIf you miss it
Rouvrir la paireReopen the pairv, ok := x.(T) — la forme à deux retours, par défaut.v, ok := x.(T) — the two-result form, by default.L'assertion nue panique dès que le type ne colle pas.The bare assertion panics the moment the type doesn't match.
Le type switchThe type switchswitch x.(type) dès qu'il y a plusieurs types à router.switch x.(type) as soon as several types must be routed.Des cascades de if-assertions, fragiles et répétitives.Brittle, repetitive chains of if-assertions.
Le coûtThe costLe boxing alloue, le dispatch indirige — mesure avec -benchmem.Boxing allocates, dispatch indirects — measure with -benchmem.Un []any dans une boucle chaude, et le GC trinque.A []any in a hot loop, and the GC pays the bill.
any ou génériquesany or genericsGénérique si les types partagent une forme ; any sinon.Generic if the types share a shape; any otherwise.any partout : tu perds la sûreté de type et tu asserts en sortie.any everywhere: you lose type safety and assert on the way out.
Le volume 3 posait une question : qui possède l'abstraction ? Réponse : celui qui s'en sert — et il en connaît aussi le prix.Volume 3 asked one question: who owns the abstraction? Answer: whoever uses it — and they know its price too.
Mot de l'éditeurFrom the editor

Trois numéros sur l'interface pour préparer la seule qui compte vraiment au quotidien : error.Three issues on the interface to prepare the only one that truly matters daily: error.

Le volume 3 a l'air d'un détour théorique — satisfaction implicite, paire de mots, boxing, génériques. Il ne l'était pas. C'était la mise en place patiente d'un seul outil, pour pouvoir, au volume suivant, le braquer sur le problème le plus concret de la programmation Go : les erreurs. Car error n'est rien d'autre qu'une interface à une méthode, Error() string. Tout ce qu'on vient d'apprendre s'y applique mot pour mot. Une erreur enveloppée est une valeur boxée. errors.As n'est qu'une assertion de type qui descend une chaîne. Le typed nil du numéro 2 expliquait déjà pourquoi if err != nil pouvait mentir. On n'a pas étudié l'interface pour elle-même : on a aiguisé l'outil avec lequel on va tailler la gestion d'erreurs idiomatique.Volume 3 looks like a theoretical detour — implicit satisfaction, a two-word pair, boxing, generics. It wasn't. It was the patient setup of a single tool, so that next volume we can aim it at the most concrete problem in Go programming: errors. Because error is nothing but a one-method interface, Error() string. Everything we just learned applies to it word for word. A wrapped error is a boxed value. errors.As is just a type assertion walking down a chain. Issue 2's typed nil already explained why if err != nil could lie. We didn't study the interface for its own sake: we sharpened the tool we'll carve idiomatic error handling with.

Et c'est là que la philosophie de Go se révèle pleinement. Les autres langages traitent l'erreur comme une rupture — une exception qui saute par-dessus le code normal, un canal parallèle. Go refuse ce dualisme : une erreur est une valeur comme une autre, renvoyée comme un résultat, comparée avec ==, rangée dans une variable, enveloppée dans une autre. Pas de magie, pas de pile qui se déroule en douce — juste une valeur qu'on inspecte avec les mécaniques qu'on vient de démonter. C'est cohérent avec tout le reste : en Go, on ne cache pas le contrôle, on le tient dans la main. Vol. 4 — Les erreurs sont des valeurs : on ouvre le chapitre que ce langage a écrit différemment de tous les autres.And that's where Go's philosophy reveals itself fully. Other languages treat the error as a rupture — an exception leaping over normal code, a parallel channel. Go refuses that dualism: an error is a value like any other, returned as a result, compared with ==, stored in a variable, wrapped in another. No magic, no stack quietly unwinding — just a value you inspect with the mechanics we just took apart. It's consistent with everything else: in Go, you don't hide control flow, you hold it in your hand. Vol. 4 — Errors are values: we open the chapter this language wrote unlike any other.