今日已更新 396 条资讯 | 累计 20866 条内容
关于我们

标签:#programming

找到 1376 篇相关文章

AI 资讯

Struct Embedding in Go: Composition That Bites When You Reach for Inheritance

Book: The Complete Guide to Go Programming Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You come to Go from a language with classes. You see struct embedding for the first time, and it reads like inheritance. A field with no name, methods that "carry over" to the outer type, a base struct that your type extends. So you write code the way you always have, and most of it works. Then a method does something you did not ask for, a type satisfies an interface you never meant to implement, or two embedded types fight over a name and the compiler shrugs until the exact line that calls it. Embedding is not inheritance. It is composition with a syntax that promotes methods and fields up one level. Once you hold that distinction, the surprises stop being surprises. Here is where they come from. Embedding promotes, it does not subclass Write an embedded field by giving a type with no field name: type Engine struct { Horsepower int } func ( e Engine ) Start () string { return "vroom" } type Car struct { Engine // embedded Brand string } Car now has a Start method and a Horsepower field, both promoted from Engine . You can write car.Start() and car.Horsepower as if they were declared on Car . car := Car { Engine : Engine { Horsepower : 300 }, Brand : "Fiat" } fmt . Println ( car . Start ()) // vroom fmt . Println ( car . Horsepower ) // 300 This is where the inheritance illusion starts. car.Start() is sugar. The compiler rewrites it to car.Engine.Start() . The receiver of Start is still an Engine , never a Car . There is no base class, no super , no virtual dispatch. Engine does not know Car exists. That last point is the one that bites. A promoted method runs against the embedded value, not the outer struct. The method that ignores the outer struct Say you want a stringer on the embe

2026-06-14 原文 →
创业投融资

Typescritp: Sobrecarga de Construtor

Introdução Assim como funções, construtores podem ter múltiplas assinaturas: O problema class Evento { constructor ( id : string , tipo : string , competencia : string ) { ... } // como aceitar também só id e tipo, sem competencia? } Solução — overload signatures class Evento { id : string ; tipo : string ; competencia : string ; // assinaturas constructor ( id : string , tipo : string ); constructor ( id : string , tipo : string , competencia : string ); // implementação constructor ( id : string , tipo : string , competencia : string = " nao-definida " ) { this . id = id ; this . tipo = tipo ; this . competencia = competencia ; } } new Evento ( " 1 " , " R-2010 " ); // ✅ primeira assinatura new Evento ( " 1 " , " R-2010 " , " 2024-01 " ); // ✅ segunda assinatura

2026-06-14 原文 →
AI 资讯

defer in Loops: The Resource Leak Go Still Lets You Write

Book: The Complete Guide to Go Programming Also by me: Thinking in Go (2-book series) — Complete Guide to Go Programming + Hexagonal Architecture in Go My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools Me: xgabriel.com | GitHub You wrote a function that walks a directory and reads every file. It opened cleanly in review. It passed tests on a fixture folder with three files. Then a customer pointed it at a folder with 20,000 files, and the logs filled with: open /data/batch/img-08431.png: too many open files The code never closed anything early. It deferred every close. And that is exactly the problem. defer runs at function return, not end of iteration defer schedules a call to run when the surrounding function returns. Not when the current block ends. Not when the loop iteration ends. When the function returns. Most of the time that distinction does not matter, because most deferred calls live in short functions that return quickly. Put a defer inside a for loop, though, and every iteration adds one more deferred call to a stack that does not unwind until the whole loop is done and the function exits. Here is the version that ships: func processFiles ( paths [] string ) error { for _ , p := range paths { f , err := os . Open ( p ) if err != nil { return err } defer f . Close () // runs at RETURN, not here if err := handle ( f ); err != nil { return err } } return nil } Read it the way the language reads it. On the first iteration, os.Open returns a file handle and you defer its close. On the second iteration, another handle, another deferred close. By the time the loop has touched 20,000 files, you are holding 20,000 open descriptors, and not one of them closes until processFiles returns. Your process has a file-descriptor limit. On Linux the soft default is often 1024. You blow through it somewhere around the 1024th file, and the error you get back says nothing about defer . It says too many open files , wh

2026-06-14 原文 →
AI 资讯

Types of loops in JS

Programming is all about solving problems efficiently. Two concepts that play a major role in writing reusable and efficient programs are loops and functions . Loops help us perform repetitive tasks without writing the same code again and again, whereas functions help us organize code into reusable blocks. Let's understand these concepts in detail. Why Do We Need Loops? Suppose we want to print "Hello" five times. Without loops, we would write: console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); console . log ( " Hello " ); Although this works, it violates one of the fundamental principles of programming: Don't Repeat Yourself (DRY) Repeating code: Increases the number of lines. Makes maintenance difficult. Introduces more chances for errors. Loops solve this problem by allowing us to execute the same block of code multiple times. Types of Loops in JavaScript JavaScript provides three looping statements: Loop Type Category while Entry-Check Loop for Entry-Check Loop do...while Exit-Check Loop Entry-Check Loop / Entry-Controlled Loop In entry-Check loops, the condition is checked before executing the loop body. If the condition is false initially, the loop body never executes. Examples: while loop for loop Exit-Check Loop / Exit-Controlled Loop In an exit-Check loop, the loop body executes first and then checks the condition. Therefore, the body executes at least once. Example: do...while loop Components of Every Loop Every loop generally consists of three parts: 1. Initialization Determines where the loop starts. let i = 1 ; 2. Condition Determines whether the loop should continue executing. i <= 5 3. Increment or Decrement Updates the loop variable after each iteration. i ++ ; or i -- ; 1. while Loop The while loop repeatedly executes a block of code as long as the condition remains true. Syntax while ( condition ) { // statements } Example: Print Numbers from 1 to 5 let i = 1 ; while ( i <= 5 ) { cons

2026-06-14 原文 →
AI 资讯

Reading a Paginated API Without Holding the Whole Thing in Memory

Your API hands out 50 records at a time across 400 pages. You need all of them. You do not need them all at once. Here's a very familiar situation that shows up constantly on the backend. Some API returns data in pages, 50 or 100 records at a time, and you need to walk every page: sync them to your database, export them to a file, run a report. The endpoint gives you a cursor or a page number and you keep asking until there's nothing left. The way most of us write it the first time looks like this: async function getAllRecords () { const all = []; let cursor = 0 ; while ( cursor !== null ) { const { records , nextCursor } = await fetchPage ( cursor ); all . push (... records ); cursor = nextCursor ; } return all ; } const everything = await getAllRecords (); for ( const record of everything ) { process ( record ); } It works. At four hundred records it's fine. The trouble starts when the dataset grows, and it has three separate problems hiding in it. It holds the entire dataset in memory before you touch a single record. It's all or nothing: if page 380 fails, you've thrown away the 19,000 records you already fetched . And it's eager. You can't start processing record one until the very last page has landed , even if all you wanted was the first ten. There's a shape in JavaScript built for exactly this, and if you read the first two posts in this series you already have both halves of it. Two ideas you've already seen In the CSV post , we pulled rows out of a huge file one at a time with a generator, so the file never fully loaded into memory. Lazy. Pull-based. You ask for the next row, you get the next row, nothing more. In the async/await post , we saw that a generator can pause at a yield and resume later.A generator can hold its place across an asynchronous gap. Put those together. A generator that pulls data lazily, and can pause to await something between pulls. That's an async generator, and it's the natural tool for walking a paginated API. You pull records

2026-06-13 原文 →
AI 资讯

What Happened When I Told Codex to Calm Down

I have been doing a lot of work lately tightening up my diagnostic suite: the mechanics, the workflow, the way it runs against target repos, the way it helps narrow a repair instead of letting everything turn into a fog machine. And because I work with Codex as my coding agent, I have also become very familiar with a specific kind of AI-agent behavior. The “I am helping so hard I am about to make this worse” behavior. If you work with coding agents, you probably know the vibe. You ask for one thing. The agent does that thing. Then it also adjusts a helper. Then it updates a fixture. Then it “notices” a nearby pattern. Then it starts explaining three other improvements you never asked for. And now you’re staring at the diff like: “Why are you in that file?” “I did not tell you to touch that.” “That was not the repair lane.” “Please stop being useful for one second.” I am not proud of how many times I have verbally threatened a language model. But here we are. The funny thing is, I am building Scarab partly because I already expect this kind of drift. I know that when an AI coding agent is given too much uncertainty, it tries to solve the uncertainty itself. Sometimes that is useful. Sometimes it is a raccoon with a soldering iron. The challenge is that while I am developing the diagnostic system, I cannot always use the diagnostic system to supervise itself. So there are moments where I have to manually hold the line. That means a lot of conversations with Codex that sound like: “Do not widen the patch.” “Do not change the diagnostic output to make the diagnostic pass.” “Do not fix the test by changing what the test means.” “Do not touch SDS mechanics while repairing the target repo.” “Stay in the target.” “Stay in the lane.” “Why are you like this?” Very normal. Very calm. Very professional. Then something changed At some point, after a lot of tightening, the workflow started to feel different. Scarab had enough of the diagnostic work under control that I could tell

2026-06-13 原文 →
AI 资讯

⚠️ The Kotlin Multiplatform division-by-zero trap

If you write Kotlin Multiplatform code that involves integer division, you may have already hit this: the exact same expression behaves completely differently depending on which platform compiles it. 🐛 The problem Take this innocuous expression: val quotient = 12 / 0 val remainder = 12 % 0 On JVM and Native , both lines throw an ArithmeticException . That is the behavior most Kotlin developers expect and design around. On JavaScript , both lines execute without any exception and silently return 0 . Here is a concrete illustration drawn directly from the Kotlin test suites for each platform: // Kotlin/JS check ( 12 / 0 == 0 ) // passes — no exception check ( 12 % 0 == 0 ) // passes — no exception // Kotlin/JVM and Kotlin/Native val quotient : Result < Int > = runCatching { 12 / 0 } val remainder : Result < Int > = runCatching { 12 % 0 } check ( quotient . exceptionOrNull () is ArithmeticException ) // passes check ( remainder . exceptionOrNull () is ArithmeticException ) // passes Summary table: Expression JVM / Native JavaScript 12 / 0 ArithmeticException 0 12 % 0 ArithmeticException 0 🤔 Why it happens On Kotlin/JS, Int values are represented as JavaScript numbers, and 12 / 0 evaluates to Infinity while 12 % 0 evaluates to NaN . Kotlin/JS truncates Int arithmetic to 32 bits using JavaScript's | 0 operator, and per the ECMAScript ToInt32 conversion, both Infinity | 0 and NaN | 0 evaluate to 0 — so the division-by-zero result silently becomes 0 , with no exception thrown. JVM and Native follow Java's long-standing contract: integer division by zero is always an ArithmeticException . The practical consequence is that any guard you write and test on JVM — a try/catch(ArithmeticException) or a pre-condition check that relies on an exception — is silently bypassed when the same code runs on JS. No compile error, no warning, just a wrong result. ✅ The fix: Integer from Kotools Types 5.1.1 The Integer type in Kotools Types explicitly checks for a zero divisor before delegat

2026-06-13 原文 →
开发者

The Rust You Actually Need to Write Your First Anchor Program

If you have made it this far in 100 Days of Solana, you have been working in JavaScript and on the command line. You have been calling RPC methods, building instructions, signing transactions, and reading and writing account data in JavaScript, and most recently minting and sending tokens and NFTs from the CLI. Either way, you have been driving Solana with tools that let you assign a value and move on with your life. Soon the ground shifts. You are going to open a file called lib.rs , and it is going to be Rust, and for a day or two it is going to feel like you forgot how to program. That feeling is normal, it is temporary, and it is not a sign you are in the wrong place. Here is the thing nobody says out loud: you do not need to learn all of Rust to write Solana programs. Rust is a big language with a steep reputation, but the slice of it that shows up in an Anchor program is small and repetitive. You will see the same handful of patterns on almost every line. Learn those patterns and the wall turns back into a floor. This post is that handful. Not a Rust course, just the parts you need to read your first Anchor program and understand what every line is doing. Next week we start Arc 9, the Anchor introduction, where this all becomes real. This week is about making the language stop being scary before you get there. Why it feels like a wall JavaScript is dynamically typed and garbage collected. You write const x = 5 , you never tell anyone it is a number, and when you are done with it the runtime quietly cleans up. The language trusts you and sorts out the consequences at runtime, which is why a typo surfaces as undefined is not a function three minutes into a demo. Rust is the opposite philosophy. It is compiled and statically typed, so every value has a type the compiler knows about before the program ever runs, and it has no garbage collector, so it tracks who is responsible for every piece of memory through a system called ownership. The trade is blunt: Rust mak

2026-06-13 原文 →
AI 资讯

Analysis of how code duplication changed in recent years (no clear trend)

My methodology and data set didn't show any trend, but it demonstrated a more important issue: how wrongly this kind of research can be done and how misinterpreted the conclusions can be. The reason for making this research was an attempt to verify the claim that AI-assisted development increases code duplication. I analyzed 14 well-maintained open-source projects between 2021-2026, excluding new ones developed only with AI. For duplication detection, I compared semantic similarity using https://github.com/rafal-qa/slopo (I'm the author), not exact copies. This data can't prove or deny the claim, no trend is visible. Not only because 14 projects is too little, but also because there is a large variance between projects. The main advantage of this research is that it highlights the pitfalls in the analysis and conclusions and shows how easy it is to create "evidence" to support any claim. submitted by /u/rafal-kochanowski [link] [留言]

2026-06-13 原文 →
AI 资讯

What Nobody Told Me About Maintaining an Open Source Project

I am a solo learner. I started coding last year with the help of AI and sometimes without any tutorials or courses. At first, I thought this journey would be easier. But soon I realized something important — no AI or tool can fully solve the real problems I was facing as a developer. I used AI a lot. It explained things with confidence and even provided code. But when I ran that code in my terminal, many times it didn’t work. That’s when I understood something important: AI can guide, but it cannot replace understanding. After facing these issues, I changed my way of learning. Instead of blindly trusting AI, I started: Finding real open-source projects Studying how they were built Listing important topics from those projects Reading documentation carefully Asking AI to explain specific lines of code This helped me understand real-world code better. From this learning journey, I realized something: I should also build my own open-source projects. At first, I believed that creating a powerful project could automatically bring attention and users. But I was wrong. I made a mistake — I was not active on any platform. I was just coding inside VS Code, without communication or sharing my work anywhere. Then I realized: Being a developer is not only about coding. Visibility and communication are also important. After that realization, I started being active on platforms like Dev.to, LinkedIn, and other developer communities. I started posting my work and sharing my progress. Even though I didn’t get many comments, I started getting reactions and engagement. That small feedback gave me motivation. From this journey, I learned something important: Open source is not only about code. It is about helping other developers, sharing knowledge, and being consistent and visible. A developer should not only code silently but also participate in the community. Now I understand that coding is only one part of being a developer. Community, communication, and consistency are equally imp

2026-06-13 原文 →
AI 资讯

Why Retry Is One Of The Most Dangerous Keywords In Software

Few lines of code look more innocent than this: retry ( 3 ) It feels responsible. Professional. Resilient. After all, networks fail. Servers become unavailable. Databases occasionally time out. Retrying seems like the obvious solution. And sometimes it is. But after enough years building production systems, I've become convinced of something: Retry is one of the most dangerous keywords in software. Not because retries are bad. Because retries amplify everything. Good systems become more reliable. Bad systems become disasters. The problem is that many developers treat retries as a reliability feature when they're actually a distributed systems feature. And distributed systems are where simple ideas go to become complicated. Why Retries Exist Imagine: await fetch ( " /api/users " ); The request fails. Maybe: Network hiccup Temporary database issue Load balancer restart Service deployment The operation might succeed if attempted again. So we write: retry ( 3 ) Seems reasonable. And in many cases: It Works Which is why retries become popular. The Dangerous Assumption Most developers unconsciously assume: Failure = Operation Did Not Execute Unfortunately that's not always true. A request can: Execute Successfully ↓ Response Never Arrives From the client's perspective: Failure From the server's perspective: Success Now a retry becomes dangerous. The Double Payment Problem Imagine a payment service. await chargeCard ( order ); The card processor successfully charges: $100 The response is lost due to a network issue. Client sees: Request Failed and retries. await chargeCard ( order ); again. Now: Charge #1 = Success Charge #2 = Success The customer paid twice. Nobody wrote bad logic. The retry created the bug. The Email Storm Problem Consider: await sendWelcomeEmail ( user ); Email provider accepts the message. Response times out. Application retries. await sendWelcomeEmail ( user ); again. Customer receives: Welcome! Welcome! Welcome! Welcome! Support ticket created. Marke

2026-06-13 原文 →
AI 资讯

Not Your Weights, Not Your Workflow

I left a multi-agent refactor running overnight. By morning the model was gone, pulled out from under me by a government I don't even vote for, on the other side of an ocean. This isn't really a story about Anthropic. It's a story about who's actually holding the off-switch, and right now it probably isn't you. So here's how my morning went. I had a job running. Not a toy, a proper codebase-wide refactor that had been grinding away continuously for the best part of two days. Multi-agent setup, left to run overnight, the kind of long, messy, long-horizon task that every model before this one just fell over on. Claude Fable 5 was handling it like it was nothing. Anthropic's own launch notes talk about it compressing months of work into days, and honestly, on my own codebase, that wasn't marketing. It was just what was happening. Then I woke up. And the model was gone. Not rate-limited. Not having a wobble. Gone. The thing I'd built two days of momentum on simply did not exist any more. Turns out that on the 12th of June the US government issued an export-control directive telling Anthropic to cut off all access to Fable 5 and Mythos 5 for any foreign national. And because you can't exactly sort a global user base by passport in real time, that meant pulling it for everyone. Including me, sat in Tyrol, watching my overnight run go cold. Anthropic did the right things, for what it's worth. They complied fast, they said out loud that they disagreed, and they're fighting to get it back. About as well as a vendor can behave in that situation. (As I write this it's still down. Anthropic reckon it's a misunderstanding and they're trying to get it restored, so maybe by the time you read this it's back up. Doesn't change a single thing about the point I'm making.) And it made absolutely no difference to me. That, right there, is the whole point of this post. The offer was the trap Wind back a few days. Fable 5 dropped as the best model anyone had shipped, and the offer was lov

2026-06-13 原文 →
AI 资讯

I Lost 30% of My UDP Packets — and the Network Was Innocent

A receiver pulling a UDP feed was missing roughly 30% of its messages. No errors, no exceptions, no stack traces — just gaps in the sequence numbers. The first suspect is always the network: a flaky switch, a saturated link, a tired NIC. The network was innocent. The packets were being dropped on the receiving host , after they'd already arrived. Here's how to tell the difference, and why it matters. Why UDP makes this sneaky UDP has no retransmission and no backpressure. When a datagram is lost, nobody is notified — not the sender, not the receiver. The packet simply isn't there. That means two completely different failures look identical from the application's point of view: The network dropped the packet before it reached your machine. Your own host accepted the packet and then threw it away after it arrived. The application sees the same thing in both cases: a missing sequence number. But the fix is in a different building depending on which one it is. Where the packets actually go The receive path is: NIC → kernel socket receive buffer → your recv() call. The kernel parks incoming datagrams in a per-socket buffer until your code reads them. If your code doesn't drain that buffer fast enough, it fills, and the kernel drops the overflow. Crucially, the kernel counts those drops. On Linux: # Per-protocol summary — look for "receive buffer errors" netstat -su # Or straight from the kernel counters cat /proc/net/snmp | grep -A1 Udp # InDatagrams ... InErrors RcvbufErrors ... If RcvbufErrors is climbing, the network did its job and your host discarded the datagrams. That single counter collapses a week of "is it the switch?" into about ten seconds of certainty. The actual cause In this case the socket receive buffer was sitting at the default (~208 KB). The sender burst faster than a single receive thread could call recv() . Average throughput looked fine on every dashboard — but the bursts filled the buffer in milliseconds, and everything past the brim was dropped.

2026-06-13 原文 →