go语言简单示例

十一文 2013-08-20 11:40:12


本帖子内容都是翻译自此网站https://gobyexample.com/(翻译水平有限,请多见谅),内容如下:


go语言示例


go语言是一个开源的语言。专为简单,迅速的编译可靠的软件而设计。

本例具有操作介绍和注释,你可以直接看第一个例子或者通过下面的列表


Hello World
Values
Variables
Constants
For
If/Else
Switch
Arrays
Slices
Maps
Range
Functions
Multiple Return Values
Variadic Functions
Closures
Recursion
Pointers
Structs
Methods
Interfaces
Errors
Goroutines
Channels
Channel Buffering
Channel Synchronization
Channel Directions
Select
Timeouts
Non-Blocking Channel Operations
Closing Channels
Range over Channels
Timers
Tickers
Worker Pools
Rate Limiting
Atomic Counters
Mutexes
Stateful Goroutines
Sorting
Sorting by Functions
Panic
Defer
Collection Functions
String Functions
String Formatting
Regular Expressions
JSON
Time
Epoch
Time Formatting / Parsing
Random Numbers
Number Parsing
URL Parsing
SHA1 Hashes
Base64 Encoding
Reading Files
Writing Files
Line Filters
Command-Line Arguments
Command-Line Flags
Environment Variables
Spawning Processes
Exec'ing Processes
Signals
Exit

...全文
14894 176 打赏 收藏 转发到动态 举报
写回复
用AI写文章
176 条回复
切换为时间正序
请发表友善的回复…
发表回复
枫树湾 2016-03-31
  • 打赏
  • 举报
回复
使用go语言开源电商系统 QOR 开发的一个demo网站 http://demo.getqor.com/admin 源码在这里:https://github.com/qor/qor-example/
我看你有戏 2016-01-21
  • 打赏
  • 举报
回复
mark 辛苦
foreachlin 2015-10-14
  • 打赏
  • 举报
回复
很好哦,学习到了
aqua2013 2014-10-13
  • 打赏
  • 举报
回复
不支持UI什么意思? 不能编写有图形化界面的程序???
www_7di_net 2014-08-28
  • 打赏
  • 举报
回复
版主很強大的說
pj199 2014-08-14
  • 打赏
  • 举报
回复
版主有没有一些go使用mongodb和meemcache的资料啊,一个mgo文档说的太少了用不起来,网上都是关于java的c++的就是没有go的
  • 打赏
  • 举报
回复
十一文 2014-07-06
  • 打赏
  • 举报
回复
go语言示例:字符串函数 标准库strings 包中包含了许多字符串相关的函数,我们在这里看看这个包的一些示例。 我们给fmt.Println 一个简短的别名,然后我们将在下面多次用到他。 这里有一些简短可用的字符串函数。注意这些函数都来自于srings包,并不是自身string对象的一个方法。这意味着我们得把字符串作为第一个参数传递给这些函数。 你可以在srings包(地址:http://golang.org/pkg/strings/ 注意:也许要上梯子)找到更多的函数。 这里也提一下,不是在stings包的但是很有价值的内置函数:获取字符串长度,和通过索引获取字符串中的字符。
// The standard library's `strings` package provides many
// useful string-related functions. Here are some examples
// to give you a sense of the package.

package main

import s "strings"
import "fmt"

// We alias `fmt.Println` to a shorter name as we'll use
// it a lot below.
var p = fmt.Println

func main() {

    // Here's a sample of the functions available in
    // `strings`. Note that these are all functions from
    // package, not methods on the string object itself.
    // This means that we need pass the string in question
    // as the first argument to the function.
    p("Contains:  ", s.Contains("test", "es"))
    p("Count:     ", s.Count("test", "t"))
    p("HasPrefix: ", s.HasPrefix("test", "te"))
    p("HasSuffix: ", s.HasSuffix("test", "st"))
    p("Index:     ", s.Index("test", "e"))
    p("Join:      ", s.Join([]string{"a", "b"}, "-"))
    p("Repeat:    ", s.Repeat("a", 5))
    p("Replace:   ", s.Replace("foo", "o", "0", -1))
    p("Replace:   ", s.Replace("foo", "o", "0", 1))
    p("Split:     ", s.Split("a-b-c-d-e", "-"))
    p("ToLower:   ", s.ToLower("TEST"))
    p("ToUpper:   ", s.ToUpper("test"))
    p()

    // You can find more functions in the [`strings`](http://golang.org/pkg/strings/)
    // package docs.

    // Not part of `strings` but worth mentioning here are
    // the mechanisms for getting the length of a string
    // and getting a character by index.
    p("Len: ", len("hello"))
    p("Char:", "hello"[1])
}
$ go run string-functions.go Contains: true Count: 2 HasPrefix: true HasSuffix: true Index: 1 Join: a-b Repeat: aaaaa Replace: f00 Replace: f0o Split: [a b c d e] toLower: test ToUpper: TEST Len: 5 Char: 101 下一个示例:字符串格式化 原文地址:https://gobyexample.com/string-functions
十一文 2014-07-06
  • 打赏
  • 举报
回复
go语言示例:集合函数

我们经常需要对数据集合进行操作,例如在自定义函数中查询满足给定的条件项或者映射所有的项到一个新集合。

在一些语言中用泛型的数据结构和算法来做这些事情。但是go不支持泛型,通常在go中,如你迫切需要,我们用几何函数来实现。

这里有一些string slice类型的集合函数的示例。你可以用这些示例来创建自己的集合函数。注意在一些情况下,用内部函数来代替创建的函数或者调用辅助函数是最直接的。

返回匹配目标字符串的第一个索引,如果没有匹配的返回-1。

如果slice中有目标字符串,返回true。

返回true,如果slice中的一个字符串满足f条件。

返回true,如果slice中的每一个字符串满足f条件。

返回新的slice,包含slice中每一个满足f的字符串。

对slice中的所有字符应用f,并返回一个新的slice。

我们在这里检验这些集合函数。

以上所有的例子都用的匿名函数,但是你也可以用有命名和类型的函数。

// We often need our programs to perform operations on
// collections of data, like selecting all items that
// satisfy a given predicate or mapping all items to a new
// collection with a custom function.

// In some languages it's idiomatic to use [generic](http://en.wikipedia.org/wiki/Generic_programming)
// data structures and algorithms. Go does not support
// generics; in Go it's common to provide collection
// functions if and when they are specifically needed for
// your program and data types.

// Here are some example collection functions for slices
// of `strings`. You can use these examples to build your
// own functions. Note that in some cases it may be
// clearest to just inline the collection-manipulating
// code directly, instead of creating and calling a
// helper function.

package main

import "strings"
import "fmt"

// Returns the first index of the target string `t`, or
// -1 if no match is found.
func Index(vs []string, t string) int {
for i, v := range vs {
if v == t {
return i
}
}
return -1
}

// Returns `true` if the target string t is in the
// slice.
func Include(vs []string, t string) bool {
return Index(vs, t) >= 0
}

// Returns `true` if one of the strings in the slice
// satisfies the predicate `f`.
func Any(vs []string, f func(string) bool) bool {
for _, v := range vs {
if f(v) {
return true
}
}
return false
}

// Returns `true` if all of the strings in the slice
// satisfy the predicate `f`.
func All(vs []string, f func(string) bool) bool {
for _, v := range vs {
if !f(v) {
return false
}
}
return true
}

// Returns a new slice containing all strings in the
// slice that satisfy the predicate `f`.
func Filter(vs []string, f func(string) bool) []string {
vsf := make([]string, 0)
for _, v := range vs {
if f(v) {
vsf = append(vsf, v)
}
}
return vsf
}

// Returns a new slice containing the results of applying
// the function `f` to each string in the original slice.
func Map(vs []string, f func(string) string) []string {
vsm := make([]string, len(vs))
for i, v := range vs {
vsm[i] = f(v)
}
return vsm
}

func main() {

// Here we try out our various collection functions.
var strs = []string{"peach", "apple", "pear", "plum"}

fmt.Println(Index(strs, "pear"))

fmt.Println(Include(strs, "grape"))

fmt.Println(Any(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))

fmt.Println(All(strs, func(v string) bool {
return strings.HasPrefix(v, "p")
}))

fmt.Println(Filter(strs, func(v string) bool {
return strings.Contains(v, "e")
}))

// The above examples all used anonymous functions,
// but you can also use named functions of the correct
// type.
fmt.Println(Map(strs, strings.ToUpper))

}


$ go run collection-functions.go
2
false
true
false
[peach apple pear]
[PEACH APPLE PEAR PLUM]



下一个示例:字符串 函数
原文地址:https://gobyexample.com/collection-functions
好好学习一下 2014-04-20
  • 打赏
  • 举报
回复
飃颻 2014-04-17
  • 打赏
  • 举报
回复
引用 164 楼 xming4321 的回复:
先进后出
能不能举个示例。
十一文 2014-04-17
  • 打赏
  • 举报
回复
引用 163 楼 mingxyzonline 的回复:
当一个函数或者方法中同时出现多个defer语句, 各个defer语句执行顺序是先进先出,还是后进先出。
先进后出
飃颻 2014-04-17
  • 打赏
  • 举报
回复
引用 164 楼 xming4321 的回复:
先进后出
经查阅有关资料,说法一致。
飃颻 2014-04-15
  • 打赏
  • 举报
回复
当一个函数或者方法中同时出现多个defer语句, 各个defer语句执行顺序是先进先出,还是后进先出。
飃颻 2014-04-14
  • 打赏
  • 举报
回复
Go语言将错误和异常两者区分对待。 错误是指可能出错的东西,程序需以优雅的方式将其处理。 (例如,文件不能被打开) 而异常是指“不可能”发生的事情。 (例如,一个应该永远为true的条件在实际环境中却是false的) 摘自许式伟翻译的《Go语言程序设计》
十一文 2014-04-14
  • 打赏
  • 举报
回复
go 语言示例: 异常

异常通常意味着发生了一些我们不想发生的错误。大多数情况下,我们用它来快速的返回运行期间本不该出现的故障,或者我们根本就不准备处理。

我们将在这里用异常来检查非预期的错误。在这里用设计给异常的唯一调用方式调用。

异常的一个常见的用途是终止程序,当一个函数返回一个我们不知道怎么处理的异常的时候。这里有一个例子,他用在当我们害怕在创建一个文件时候返回一个未知错误的时候。

package main
import "os"
func main() {

panic("a problem")

_, err := os.Create("/tmp/file")
if err != nil {
panic(err)
}
}


运行这个程序会导致一个异常,然后打印出错误和goroutine栈,并返回非零值。
$ go run panic.go
panic: a problem
goroutine 1 [running]:
main.main()
/.../panic.go:12 +0x47
...
exit status 2


注意:它不像一些语言样,用异常来处理很多错误。在go语言一般尽可能的声明错误的返回。

下一个示例:Defer
原文地址:https://gobyexample.com/panic
十一文 2014-04-14
  • 打赏
  • 举报
回复
引用 157 楼 u012619303 的回复:
有想学的冲动~~~
别 冲动 直接上!
十一文 2014-04-14
  • 打赏
  • 举报
回复
go语言示例:defer defer 用来确保一个函数会在程序执行完不调用,通常用来确保清理环境。defer通常就像别的语言中的finally和ensure。 例如我们创建一个,写入内容,并希望完了以后关闭文件,这里就可以用defer来实现。 在创建了文件对象后,我们立即用defer关键字调用了clodeFile函数。在writeFile执行完毕以后,它将在关闭函数(main)的最后被执行。
package main
	import "fmt"
	import "os"
	 
	func main() {
		f := createFile("/tmp/defer.txt")
		defer closeFile(f)
		writeFile(f)
	}
	func createFile(p string) *os.File {
		fmt.Println("creating")
		f, err := os.Create(p)
		if err != nil {
			panic(err)
		}
		return f
	}
	func writeFile(f *os.File) {
		fmt.Println("writing")
		fmt.Fprintln(f, "data")
	}
	func closeFile(f *os.File) {
		fmt.Println("closing")
		f.Close()
	}
运行这个程序来确认文件是否在写过后背关闭。 $ go run defer.go creating writing closing 下一个示例:集合函数 原文地址:https://gobyexample.com/defer
十一文 2014-04-14
  • 打赏
  • 举报
回复
引用 160 楼 mingxyzonline 的回复:
Go语言将错误和异常两者区分对待。 错误是指可能出错的东西,程序需以优雅的方式将其处理。 (例如,文件不能被打开) 而异常是指“不可能”发生的事情。 (例如,一个应该永远为true的条件在实际环境中却是false的) 摘自许式伟翻译的《Go语言程序设计》
恩 这个说法 好懂些。
五锅锅 2014-04-11
  • 打赏
  • 举报
回复
有想学的冲动~~~
加载更多回复(126)

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧