15 ms·
Go run
- skybrian 3y agoFor TypeScript, "deno run" seems much the same? (It's only a subset of the JavaScript ecosystem, but you can import a lot of npms nowadays.)
- vaughnegut 3y agoiirc a lot of deno is inspired by the good parts of go, so that's not an accident
- CraftThatBlock 3y agoAnd npx tsx index.ts for TypeScript, which supports ESM (although it does pull tsx)
- denysvitali 3y ago`go run main.go` breaks if your `main` module is divided into multiple files. Use `go run .` instead - it's shorter and it works with multiple files
- pizzafeelsright 3y agoHuh. Learned something today. Thank you.
- pizzafeelsright 3y agoHuh. Learned something today. Thank you.
- breadchris 3y agogreat point, this is the one thing that I wish was more intuitive. You don't have to do this if main.go is the only file in the main package and all other code is referenced by a package.
- aeturnum 3y agoThis is a good tip! It also captures what has been frustrating about golang for me. The language feels a bit stuck between simple default cases and allowing complexity. I feel like there are two relatively distinct populations of go developer: those who love how easy it is to start (true!) and those who are frustrated by the compromises the language has made to allow for more complex cases (required!). There's also a hidden third population of people who no longer sing the praises of golang as a simple, straightforward language but accept its compromises and write productive code with it. Those people, I think, write fewer viral blog posts.
- mseepgood 3y agoI don't get it. The default case is simple (go run .), and the complex case (specifying the relevant .go files one by one) is a little bit more complex. What's frustrating with that?
- skissane 3y ago> I don't get it. The default case is simple (go run .), and the complex case (specifying the relevant .go files one by one) is a little bit more complex. What's frustrating with that? The problem is many Go tutorials start out by teaching the complex case first and leave the simple case to later (if they cover it at all).
- rtheunissen 3y agoMaybe it is because the simple way requires knowledge of packages, which are covered later perhaps, since many tutorials go straight to "go run helloworld.go"
- skissane 3y agoYou don't need to cover packages. You could just say this: the standard convention is that the source for each Go program lives in its own directory, and it starts running the code in a file called `main.go`. To run the Go program in the current directory, run `go run .` Introducing the concept of "packages", and the fact that the directory is a package, can be deferred until later.
- IggleSniggle 3y agoYup. This was the main thing that bit me when I was first getting into Go. File names are kind of like classes, and directories are kind of like modules. The encapsulation sits at a slightly different layer than you might expect.
- mseepgood 3y agoYour expectations may vary depending on where you come from. There are many places one can come from. It's advisable to minimize expectations or assumptions when learning something new, as they could impede your learning process.
- lanternfish 3y agoOn the other hand, learning something tabula rasa takes way longer than if you scaffold it with assumptions. Otherwise, each new skill/language you learn would take as long as the first one.
- IggleSniggle 3y agoYes, absolutely. Thank you for clarifying what I was saying. Regardless of where you are coming from, it's likely to be the places where there unstated assumptions / cultural-norms that differ from your own where you will experience the biggest "lift" when encountering a new technology. The more a culture aligns with a "lowest common denominator," the more it will be readily understood, and the less it does, the more it will act as an exclusivity gate. Either could be desirable or undesirable depending on your goals. It's good to be aware of the dynamics so that you can make an informed choice about how to present your code.
- deleted 3y ago[deleted]
- ktm5j 3y agoIt's natural to have expectations based on your experiences.. I think the person you replied to is just trying to help people who might misunderstand go based on those expectations. I think you're getting unnecessarily deep here.
- 38 3y agoyou can also do `go run hello.go world.go`, but yeah `go run .` is probably better
- c314 3y ago[dead]
- devjam 3y agoAnd if your main.go is in a sub-directory, e.g. cmd/pathto/cli/main.go: $ go run ./cmd/pathto/cli
- lloeki 3y agoIsn't it supposed to be `go run ./...`? (long time I didn't use Go, back then at least, using `.` instead of `./...` could cause subtle issues)
- SPBS 3y agoFun fact: `go run .` was retrofitted on after `go run main.go` because go run was initially designed to only accept explicit filenames as an argument [1]. I can't imagine how people used to use `go run` without the ability to specify whole packages (globs don't work well because it includes test files as well). > Potential design based on discussion with proposal review: > go run [go flags] [single-package-or-*.go-list] [subprocess flags] before that it was just > go run [go flags] [*.go-list] [subprocess flags] [1] https://github.com/golang/go/issues/22726 https://github.com/golang/go/issues/22726
- lenkite 3y agoWish `go run` worked for hashbang shell scripts. But you have to do a lot of hacks to make it work like: https://gist.github.com/posener/73ffd326d88483df6b1cb66e8ed1e0bd https://gist.github.com/posener/73ffd326d88483df6b1cb66e8ed1... describes
- 1vuio0pswjnm7 3y agoThis is not a tip. It comes straight from go help run "usage: go run [build flags] [-exec xprog] package [arguments...] Run compiles and runs the named main Go package. Typically the package is specified as a list of .go source files from a single directory, but it may also be an import path, file system path, or pattern matching a single known package, as in 'go run .' or 'go run my/cmd'." Nothing is said about go run main.go.
- JBorrow 3y agoThis isn't a benefit of go, but rather a drawback of the counter-example of typescript... All tools generally designed to work for creating small utilities ({ba,z,...}sh, python, perl, go, swift, ...) have this feature.
- parkcedar 3y agoMost of these examples don’t automatically fetch the dependencies. Having come from Python, Go’s tools are notably simple.
- pdonis 3y ago> Most of these examples don’t automatically fetch the dependencies. Quite frankly, I don't want to automatically fetch dependencies at the same time I am running the code. IMO those should be separate steps, and combining them together in one is not a good idea.
- codegeek 3y agoWhy not ?
- _ache_ 3y agoWhat happens when the dependency are updated and not compatible anymore ?
- mseepgood 3y agoA Go module specifies the exact versions of its dependencies. These versions do not change unless the author explicitly updates them.
- vaughnegut 3y agoThat's why you have a go.mod file that specifies the dependencies for you. Just run go mod tidy and it generates/updates it for you. You get these reproducible builds for free this way.
- mqus 3y agoI don't think it's simple. Just `go run` would be far more simple. Right now I first have to figure out if its `go run .` or `go run cmd/main.go` or some other thing.
- cpuguy83 3y agoThis one was voted down but there is a good point here. There is no way to figure out what binaries there are (maybe you could make `go list` show all the `package main`s?, not sure). Beyond that there's no way to discover what build flags may be needed to give you the binary that the developer intended. Be it tags, ldflags, cgo support.
- NewJazz 3y agoTemporary gopath, "go install ./...", list contents of bin.
- lynndotpy 3y agoThis is what Rust does with `cargo run`; I think Poetry for Python tries to do the same thing but I haven't used it in awhile.
- thayne 3y agoThat is how `cargo run` for rust works by default. As long as there is just one executable. If you have multiple executables in a project you do need to specify which one though.
- ryukoposting 3y agoOr, even better, `./main`
- dewey 3y agoThat's not better but confusing as the "main" binary doesn't exist (The main point of go run), and you'd always have to type the full name as you can't autocomplete it.
- madeofpalk 3y ago> Yeah, and then what happens if you want to use modern syntax like esmodule [...] You are going to have to use npm. Why? Node's had built-in support for ES Modules for eons now. Everything's easy when you stick to default tooling, duh, like `node run.js` or `go run.go`. You'll loose that `go run.go` the moment you need code generation.
- floating-io 3y ago> You'll loose that `go run.go` the moment you need code generation. Not really. //go:generate ... It's pretty handy.
- bjackman 3y agoIt's not really a Go thing but a build system thing. It's useful to have your build system know what is an "executable target" and how to run it. Bazel does this for _all_ languages. I'm sure most other modern generic build systems do too. AFAIK "go run" is trivial and for single-file scripts it's fine. But for more complex cases (like the NPM equivalent thing) I actually think it's a bit of a shame that it's even needed. I don't really know why we have per-ecosystem build systems (Maven, Go, cargo, whatever the hell you're supposed to do in Python these days, the nebula of web front-end tooling, etc etc). Admittedly I do not really know the ins and outs of any of these systems in detail. I'm sure there are some good reasons why they exist under the hood.
- IggleSniggle 3y agoI'm not sure there really is a good technical reason they exist. It's cultural. It basically goes like this: - the inventor of new language 'coolang' has a way that they make their project - it's kinda messy, so they clean it up into a tidy script with a few clear and straightforward commands and/or flags, and give you "cool build," "cool install" for making sure all the necessary dependencies are present, etc - a community builds around coolang organically - everybody is so used to running "cool build" that that's just how it's done. New features get added around these conventions It's cultural, that's all it is. But like all small tight knit communities, it's important to understand the culture of the community in order to engage with it on its own terms. Its just humans being humans.
- giovannibajo1 3y agoThere's also a technical reason, which is that the build system is written in the language it targets. So the cool tool is written in coolang. That's obviously not required, you could use any programming language for the cool tool, it just happens that all people that care about the cool tool, understand the needs of the ecosystem, have issues with missing features etc. already have a non zero intersection of languages they know of: they all know coolang. If coolang decided to try to add coolang support to Bazel instead, they would probably have to learn Java[1]. Current maintainers or contributors to Bazel don't know coolang, and they don't care about it much, especially in the early stage. And maybe coolang developers don't know Java, or even actively hate it with a passion (that's why they were on the market for a new language). And even if some coolang developer decided to contribute to Bazel, the barrier would be much higher: being a mature build system with so many features and different needs, surely working in it is going to be complex; there will be many different concepts, and layers, and compromises, and APIs to work with. So for them it just makes more sense to use coolang so that all coolang developers can contribute to it having a real need for the cool tool to improve. [1] I know nothing of Bazel. So just bare with the example even if it's technically not correct.
- moondev 3y agocombined with gosh - a golang shell interpreter it's pretty easy to create scripts that run on all the platforms and architectures, even future targets go run mvdan.cc/sh/v3/cmd/gosh@latest -c ' go run github.com/mikefarah/yq/v3@latest n foo.bar.hello world | go run github.com/cezarsa/glolcat@latest'
- GorsyGentle 3y agoExcept I cannot `go run ~/that/project/over/there` as the use of go modules means I have to change directory to be inside the package first. I'm not sure why that is exactly, but it's always been a nit I've found frustrating.
- 38 3y agothats mostly true. you need to at least be at the top level of the module to do go run. any higher and you get a missing go.mod error.
- randomdata 3y agoEspecially when you can `go run that/project/over/there@latest` Although, with slight modification, you can `go run -C ~/that/project/over/there .`
- deleted 3y ago[deleted]
- zer00eyz 3y agogo build is great too! I recently was dealing with some docker containers that we needed to abuse. The app within the containers was not returning helpful errors. One quick script and a go build later I had a portable binary that could return a responsible error message.
- attilakun 3y agoI often feel like Docker shouldn't even be needed for Go apps. It's just so easy to have your dependencies in order if everything is statically linked.
- dwrodri 3y agoTangentially related: I am currently scoping out an idea for how language models could be used to augment decompilers like Ghidra. At a surface level, this was partially an intellectually interesting project because it is similar to a language translation project, however instead of parallel sentence pairs, I will probably probably be creating a parallel corpus of "decompiled" C code which will have to be aligned to the original source C code that produced the binary/object file. Then I realized, the only way I could reasonably build this corpus would be by having some sort automated flow for building arbitrary open source C projects... Perhaps I will attempt this project with a Go corpus instead.
- breadchris 3y agoan interesting project. go contains many source artifacts which make decompilation a bit more straight forward as well. I havent seen anyone really attempt this for go, but would be notable research
- dwrodri 3y agoIf it turns out that its easier for a language model to translate "Ghidra C" into readable Go code than to deal with CMake/Bazel/GNU autoconf/Ninja/Apache Meson/etc I wonder if that says more about the language model or the state of C/C++ toolchains...
- Simplicitas 3y agoGo haters are in full display with this one. LOL "go run" is yet another wonderful feature of an awesome language.
- fuzztester 3y agoMaybe. Now, go run.
- endgame 3y agoWait until you discover `nix run`. If I want to one-shot a command and not even worry about dropping into and out of a shell: `nix run nixpkgs#file some_mystery_file.xyz` will do the trick.
- gumby 3y agoYou can build the equivalent simple c++ program by just calling `make` with no arguments. Though TBF then you have to type ./a.out, and so then you want to do `make && ./a.out` and then...
- fuzztester 3y ago>so then you want to do `make && ./a.out` and then... Shell scripts ...
- cxr 3y ago> One of the understated features go run is that it will automatically download any dependencies the code references; how cool is that! All this plus talk about non-standard JS runtimes like Node, but no mention that this is how browsers have worked almost forever.
- skybrian 3y agoJavaScript started out as an interpreted language but ended up more like a compiled language due to minifying, TypeScript, JSX/TSX, and so on. So it's not simple anymore. At this point, URL imports are actually bad due to the confusion between source and compiled code. Ideally, imports should always point to source code. Bundling / minification should happen at the application level; it's not a library concern. So in that sense, Go's a lot cleaner since it's always been a compiled language.
- cxr 3y agoGo (the language) is a lot "cleaner" (than JavaScript, the language—and not the various runtimes, previously mentioned in the earlier comment), because with Go (the language), there's more code mangling going on.
- cjk 3y agoYeah, IMO, `go run` is a really under-appreciated part of what makes Go productive and low-friction. That, and the ability to cross-compile without installing a cross-toolchain for the target platform. Having spent an inordinate amount of time writing build systems and compiling/distributing cross-toolchains, this is a _huge_ deal.
- iansinnott 3y ago> what happens if you want to use modern syntax like esmodule, or maybe you want to use types with typescript? You are going to have to use npm. Shout out out to Bun (and Deno too?) for allowing you to treat typescript as an interpreted language. Great for scripting with all the bells and whistles. (Go is great, just pointing out that running TS does not actually require NPM anymore)
- declan_roberts 3y agoI love it! Go is simple. Sometimes too simple, but that works for me. I do see makefiles periodically like the author notes, but that’s almost always related to secondary build objectives, such as cross-compile or containers etc.
- shpx 3y agoClicking is my favorite part of JavaScript. I just move my mouse onto some blue text and click and the software that I want to use is installed/updated and runs, usually in under a second. In the 50+ year history of software development I haven't heard of any other software stack has been able to realize this is important. go run is close but it's still 10 times slower, maybe even 100 times slower, depending on if you want to count the git clone and how good you are at typing.
- ivanjermakov 3y agoWhat blue text has to do with JavaScript? You can create such straughtforward tool for any language, and it's running shell commands under the hood in all cases.
- jitl 3y agohere's a gray text that will install and run a javascript app when you click it, in fractions of a second: https://natto.dev/ https://natto.dev/
- badrequest 3y agoNone of this is part of Javascript, Goland does most of what you describe.
- 999900000999 3y agoGolang is such a elegant language. But comparing it to JavaScript isn't fair. JavaScript has paid my bills for years, but it's held together by collective hope. The only thing missing is a decent mobile framework. I'm using Fyne, but it just looks dated. At least for my current app it's functional though.
- bottlepalm 3y agoEh, I still don't get it. Go seems too high level for low level work - use Rust, manage your own memory, no garbage collector. Go also seems too low level for high level work - use TypeScript with all the nifty ES6 features, powerful type system, exceptions, etc.. Where does Go fit in here?
- Sxubas 3y agoGo makes error handling explcit, which is a very important part of development. Not only this makes you more conscious on thinking what you need to do when something goes wrong, but also makes codes more maintainable in my opinion. I strongly prefer go error handling compared to a throws-type-error-handling language. Also, with this comment I hope to get some pushback: I haven't kept up with the latest typescript, python or any other language features. I'm talking from almost a purely ignorant perspective so I hope to learn a bit more on how developing with other languages feels like.
- ilovejava 3y ago[dead]
- scubbo 3y ago> Also, with this comment I hope to get some pushback: I haven't kept up with the latest typescript, python or any other language features. I'm talking from almost a purely ignorant perspective so I hope to learn a bit more on how developing with other languages feels like. Can't push back there - every other language I'm aware of uses at least one (and often both) of "throwing exceptions" or "returning Result types which either contain your actual data, or an Error", both of which let you just write your logic and wrap it in a single handler rather than repeating `if err != null return _, err` everywhere (or if you _want_ to handle each error individually, you can!) I've gradually reached the conclusion that Gopher's really just do prefer GoLang's verbose repetitive approach. And, y'know what - good luck to y'all. It's not for me, but I'm trying to get better at just letting people enjoy things :)
- lopkeny12ko 3y ago> Yeah, and then what happens if you want to use modern syntax like esmodule, or maybe you want to use types with typescript? You are going to have to use npm. I don't understand what the problem is here? Every installation of Node comes bundled with npm. If it doesn't, that is a package maintenance problem. > Fun fact: One of the understated features go run is that it will automatically download any dependencies the code references; how cool is that! This feels like a massive antipattern. Why is this lauded as a "feature"? Why do I want my build system to automatically reach out to the Internet and download random code, without an explicit request to do so like "npm install"? This is even more antipattern-ish when you consider that Go dependencies are literally just repos on Github (or possibly on some random git server), instead of a centralized and moderated registry like npmjs.org. > amazing, for js we not only have npm, yarn, pnpm, and bower (am I missing any?) but we also have completely new runtimes bun and deno. So it's now considered bad to have multiple implementations of an open standard, compared to the exclusively-Google-developed Go runtime? This sounds akin to arguing in favor of a monopoly over a competitive market with consumer choice.
- asp_hornet 3y agoEveryone who clones a node project will call npm install before the call npm run. Having a seperate install command doesnt make it more secure, it just makes 1 more thing for newbies to learn and another thing to go wrong when you pull master and someone added a package and you called run without installing again.
- lopkeny12ko 3y agoIf you pull a Node project that depends on malware, "npm install" will fail, assuming npmjs has unpublished or withdrawn the malicious package. There is no such safeguard when your dependency system downloads random code from random git repos. Even worse so when this is done automatically, when a developer doesn't expect a command to do so. If I run a command that depends on a third party library or resource, and I don't have that library, I fully expect it to fail. Is that not basically universal behavior in Unix?
- pkilgore 3y ago$ cat helper.mjs export const sleep = (dur) => new Promise(resolve => setTimeout(resolve, dur)) $ cat main.mjs import { sleep } from './helper.mjs' await sleep(1000) console.log("Go is great; but weird throwing node under a bus here?") $ node main.mjs Go is great; but weird throwing node under a bus here?
- breadchris 3y agoif I were a beginner developer, I now have to have the tribal knowledge of the difference between .js and .mjs. I don't see anyone widely using .mjs to write their code either.
- BillyTheKing 3y ago$ cat helper.mjs export const sleep = (dur) => new Promise(resolve => setTimeout(resolve, dur)) $ cat main.mjs import { sleep } from './helper.js' await sleep(1000) console.log("Go is great; but weird throwing node under a bus here?") $ node main.mjs file://main.mjs:1 import { sleep } from './helper.js' ^^^^^ SyntaxError: Named export 'sleep' not found. The requested module './helper.js' is a CommonJS module, which may not support all module.exports as named exports. CommonJS modules can always be imported via the default export, for example using: import pkg from './helper.js'; const { sleep } = pkg; 'What is CommonJS?'
- BillyTheKing 3y agothis was a joke comment in the morning.. but actually just turned out to be an issue now. Was installing nanoid in a project using commonJS and typescript.. all jest tests suddenly failed. So I looked into jest.config - did I need to change something in terms of transpilation? or some new babbel config? some other secret flag somewhere? no, because turns out that npm install nanoid Nano ID 5 works only with ESM projects, in tests or Node.js scripts. For CommonJS you need Nano ID 3.x (we still support it): This whole module bit in node has been a total disaster. Incredibly frustrating
- iamjk 3y agoimo this is the biggest thing deno and bun have going for them. running typescript from the shell is so nice and easy
- brlewis 3y agoThis article would have worked a lot better without the second paragraph. The writer's simple pleasure of typing "go run ..." should not be predicated on believing that deno doesn't exist.
- BillyTheKing 3y agois anyone actually using Deno in production for larger projects?
- jobstealer 3y agodoes anyone run production code with 'go run'?
- anonyfox 3y agodepends on how you view/classify production, sometimes yes I do! if I refactor some too complicated bash script into a script.go file and then execute it against production DBs/APIs with a `go run`.
- kubanczyk 3y agoDealing like this with uncomplicated bash scripts also has a great future.
- spacebuffer 3y agoI am new to go, how do people usually run go code in production?
- brlewis 3y agoThat's missing the point. The article isn't about an advantage for large production projects.
- scubbo 3y ago> bun run :) bun hing.ts same with python but not compiled you need to install python that’s the beauty of go for me even rust you need a cargo file ...are they claiming that you can run Go without installing Go?
- tapirl 3y ago"go run" was a great way to run go code as scripts. But maybe it is not now. Why? because Go 1.22 introduced a change that breaks backwards compatibility (changing the semantics of "for;;" loops). Without language version specified (such as in go.mod files), the change will often cause unintended damage.
- todd3834 3y agoSadly I haven’t been able to write any production Go for a few years now after switching companies. However, I got bit by the seemingly innocent _platform.go “feature”. I had a file that organized a bunch of windows for a cross platform GUI app. Well it turns out something like file_windows.go only compiles on windows. Our CI environment was compiling all the code but suddenly all platforms except windows started failing. Was funny when it was diagnosed but not so funny for the time where I was deeply confused why things broke.
- alpaca128 3y ago> even rust you need a cargo file And a look at Github shows me Go has a go.mod file. I don't see the point the author wants to make, neither of them affect the build/run command.
- newzisforsukas 3y ago> But I can run node main.js? Yeah, and then what happens if you want to use modern syntax like esmodule, or maybe you want to use types with typescript? You are going to have to use npm No, you do not. You can just use .mjs extensions for esm. You can also run typescript to transpile your code and then run it with node. You can even use loaders, etc. Saying you are going to have to use the included package manager in node is probably the weakest argument for using go over node. Can you run some language superset over go magically without some transpilation? No, you cannot. You cannot build a argument comparing js to ts vs go, it doesn't follow.
- fullstackchris 3y agoyeah i was going to say its unfair from the start... node is anyway a runtime for a language... go is a language in itself, and also happens to compile to something much more flexibly runnable...
- liampulles 3y agoHelpful makefile directive... run_%: cd ./cmd/$* && \ go run .
- liampulles 3y agoPersonally I've always found it easier to do: $ go install ./... $ <cmd name>
- di-sukharev 3y agoBun run
- pusewicz 3y agoI totally clicked the link thinking I'd read about some benefits of... running. Yes, as in doing sports.
- WuxiFingerHold 3y agoGo is neat to write tools, no doubt. But I think the author is not up to date with the javascript / typescript ecosystems. npx, tsx, deno, *.mjs and bun make it convenient to run typescript tools. Bun has recently added a very interesting feature, bun shell: https://bun.sh/blog/the-bun-shell https://bun.sh/blog/the-bun-shell
- prakashn27 3y agoFrankly I put all the correct command in in package.json file based on project npm run dev is what I run all the time It was never a blocker for me