golang interface类型的动态绑定

golang其interface类型, 实现了动态绑定. 

 1 import "fmt"
 2 
 3 type ITest interface {
 4     Test()
 5 }
 6 
 7 type A int
 8 
 9 func (a *A) Test() {
10     fmt.Println(a)
11 }
12 
13 func print(t ITest) {
14     fmt.Printf("%T", t)
15 }
16 
17 func main() {
18     a := A(1)
19     print(&a)
20 }

输出结果是: 

*main.A

尤其注意, main函数中, print(&A), 如果传入A, 返回错误: "method has pointer receiver"

这里面的差别, 可以参考 http://blog.csdn.net/timemachine119/article/details/54927121

 

转载于:https://www.cnblogs.com/codesay/p/7809714.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这里是一个简单的示例,使用Golang编写GraphQL服务器: 首先,需要安装必要的依赖: ``` go get github.com/graphql-go/graphql go get github.com/graphql-go/handler ``` 然后,创建一个GraphQL的schema,定义查询和类型: ```go package main import ( "github.com/graphql-go/graphql" ) type Book struct { Title string Author string } var books []Book var bookType = graphql.NewObject( graphql.ObjectConfig{ Name: "Book", Fields: graphql.Fields{ "title": &graphql.Field{ Type: graphql.String, }, "author": &graphql.Field{ Type: graphql.String, }, }, }, ) var queryType = graphql.NewObject( graphql.ObjectConfig{ Name: "Query", Fields: graphql.Fields{ "books": &graphql.Field{ Type: graphql.NewList(bookType), Resolve: func(p graphql.ResolveParams) (interface{}, error) { return books, nil }, }, }, }, ) var schema, _ = graphql.NewSchema( graphql.SchemaConfig{ Query: queryType, }, ) ``` 在上述代码中,我们定义了一个`Book`类型和一个`Query`类型。`Query`类型有一个查询字段`books`,它返回一个`Book`类型的列表。`books`字段的解析器函数返回了一个`books`数组。 接下来,在`main`函数中,我们创建一个HTTP处理器,并将其绑定到`/graphql`路径: ```go package main import ( "encoding/json" "fmt" "net/http" "github.com/graphql-go/graphql" "github.com/graphql-go/handler" ) func main() { books = []Book{ Book{"Book 1", "Author 1"}, Book{"Book 2", "Author 2"}, } http.Handle("/graphql", handler.New(&handler.Config{ Schema: &schema, Pretty: true, GraphiQL: true, })) fmt.Println("Server is running on port 8080...") http.ListenAndServe(":8080", nil) } ``` 在`main`函数中,我们初始化了`books`数组,并创建了一个GraphQL处理器。我们将GraphQL处理器绑定到`/graphql`路径,并启动HTTP服务器。 现在,我们可以使用GraphiQL界面测试我们的GraphQL服务器了。在浏览器中打开`http://localhost:8080/graphql`,即可进入GraphiQL界面,输入以下查询语句: ```graphql query { books { title author } } ``` 点击运行按钮,即可得到以下响应: ```json { "data": { "books": [ { "title": "Book 1", "author": "Author 1" }, { "title": "Book 2", "author": "Author 2" } ] } } ``` 这是一个简单的GraphQL服务器示例,你可以根据自己的需求进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值