dongwu8653 2017-10-15 21:30
浏览 6
已采纳

何时显式实例化结构?

i'm coming from Java, and there you always do something like:

Http http = new Http(...);

http.ListenAndServe();

So all information are stored in the local variable "http".

It's different in go. There most of the information is stored directly "in another package".

You do:

import "net/http"
...    
http.ListenAndServe(...)

So you dont have to explicitly (well you could) instantiate a server struct. Just call a function from the package and all the structs will be created from there. (So compared to Java, it acts like static functions with static member variables to store all information ?)

So this is how you do it (everytime) in go ? Coming from Java, this is a little bit hard to understand. Especially when to use this method, when to use a factory pattern (like: NewHttpServer(...) ) and when to explicitly create a struct from another package ( like: var http http.Server = http.Server{...} )

Everything might be possible, but what is the idiomatic golang code ?

Is there any good document/tutorial which explains it ?

  • 写回答

2条回答 默认 最新

  • dongyuan1160 2017-10-16 03:32
    关注

    I'd really suggest reading the Godoc for net/http. The package is very feature-rich and lets you do what you want.

    The behaviour of http.ListenAndServe is to implicitly use a serve multiplexer known as DefaultServeMux, on which you can register handlers with http.Handle. So you can't deal with the server or multiplexer explicitly like this.

    It sounds like what you want (a more Java-like solution) is to instantiate a server

    s := &http.Server{
        Addr:           ":8080",
        Handler:        myHandler,        // takes a path and a http.HandlerFunc
        ReadTimeout:    10 * time.Second, // optional config
        WriteTimeout:   10 * time.Second, // ...
        MaxHeaderBytes: 1 << 20,
    }
    

    and call ListenAndServe on that:

    log.Fatal(s.ListenAndServe())
    

    Both ways are totally idiomatic, I've seen them used quite frequently.

    But seriously, don't take my word for it. Go look at the docs, they have lots of examples :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答