Go 由于不支持泛型而臭名昭著,但最近,泛型已接近成為現(xiàn)實(shí)。Go 團(tuán)隊(duì)實(shí)施了一個(gè)看起來比較穩(wěn)定的設(shè)計(jì)草案,并且正以源到源翻譯器原型的形式獲得關(guān)注。本文講述的是泛型的最新設(shè)計(jì),以及如何自己嘗試泛型。
創(chuàng)新互聯(lián)是專業(yè)的浉河網(wǎng)站建設(shè)公司,浉河接單;提供網(wǎng)站設(shè)計(jì)、成都網(wǎng)站制作,網(wǎng)頁設(shè)計(jì),網(wǎng)站設(shè)計(jì),建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進(jìn)行浉河網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴(kuò)展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團(tuán)隊(duì),希望更多企業(yè)前來合作!
例子
FIFO Stack
假設(shè)你要?jiǎng)?chuàng)建一個(gè)先進(jìn)先出堆棧。沒有泛型,你可能會(huì)這樣實(shí)現(xiàn):
type?Stack?[]interface{}func?(s?Stack)?Peek()?interface{}?{
return?s[len(s)-1]
}
func?(s?*Stack)?Pop()?{
*s?=?(*s)[:
len(*s)-1]
}
func?(s?*Stack)?Push(value?interface{})?{
*s?=?
append(*s,?value)
}
但是,這里存在一個(gè)問題:每當(dāng)你 Peek 項(xiàng)時(shí),都必須使用類型斷言將其從 interface{} 轉(zhuǎn)換為你需要的類型。如果你的堆棧是 *MyObject 的堆棧,則意味著很多 s.Peek().(*MyObject)這樣的代碼。這不僅讓人眼花繚亂,而且還可能引發(fā)錯(cuò)誤。比如忘記 * 怎么辦?或者如果您輸入錯(cuò)誤的類型怎么辦?s.Push(MyObject{})` 可以順利編譯,而且你可能不會(huì)發(fā)現(xiàn)到自己的錯(cuò)誤,直到它影響到你的整個(gè)服務(wù)為止。
通常,使用 interface{} 是相對(duì)危險(xiǎn)的。使用更多受限制的類型總是更安全,因?yàn)榭梢栽诰幾g時(shí)而不是運(yùn)行時(shí)發(fā)現(xiàn)問題。
泛型通過允許類型具有類型參數(shù)來解決此問題:
type?Stack(type?T)?[]Tfunc?(s?Stack(T))?Peek()?T?{
return?s[len(s)-1]
}
func?(s?*Stack(T))?Pop()?{
*s?=?(*s)[:
len(*s)-1]
}
func?(s?*Stack(T))?Push(value?T)?{
*s?=?
append(*s,?value)
}
這會(huì)向 Stack 添加一個(gè)類型參數(shù),從而完全不需要 interface{}?,F(xiàn)在,當(dāng)你使用 Peek() 時(shí),返回的值已經(jīng)是原始類型,并且沒有機(jī)會(huì)返回錯(cuò)誤的值類型。這種方式更安全,更容易使用。(譯注:就是看起來更丑陋,^-^)
此外,泛型代碼通常更易于編譯器優(yōu)化,從而獲得更好的性能(以二進(jìn)制大小為代價(jià))。如果我們對(duì)上面的非泛型代碼和泛型代碼進(jìn)行基準(zhǔn)測試,我們可以看到區(qū)別:
type?MyObject?struct?{
X?
int
}
var?sink?MyObjectfunc?BenchmarkGo1(b?*testing.B)?{
for?i?:=?0;?i??b.N;?i++?{
var?s?Stack
s.Push(MyObject{})
s.Push(MyObject{})
s.Pop()
sink?=?s.Peek().(MyObject)
}
}
func?BenchmarkGo2(b?*testing.B)?{
for?i?:=?0;?i??b.N;?i++?{
var?s?Stack(MyObject)
s.Push(MyObject{})
s.Push(MyObject{})
s.Pop()
sink?=?s.Peek()
}
}
結(jié)果:
BenchmarkGo1BenchmarkGo1-16?????12837528?????????87.0?ns/op???????48?B/op????????2?allocs/opBenchmarkGo2BenchmarkGo2-16?????28406479?????????41.9?ns/op???????24?B/op????????2?allocs/op
在這種情況下,我們分配更少的內(nèi)存,同時(shí)泛型的速度是非泛型的兩倍。
合約(Contracts)
上面的堆棧示例適用于任何類型。但是,在許多情況下,你需要編寫僅適用于具有某些特征的類型的代碼。例如,你可能希望堆棧要求類型實(shí)現(xiàn) String() 函數(shù)
Go語言里面定義變量有多種方式。
使用var關(guān)鍵字是Go最基本的定義變量方式,與C語言不同的是Go把變量類型放在變量名后面:
//定義一個(gè)名稱為“variableName”,類型為"type"的變量
var variableName type
定義多個(gè)變量
//定義三個(gè)類型都是“type”的變量
var vname1, vname2, vname3 type
定義變量并初始化值
//初始化“variableName”的變量為“value”值,類型是“type”
var variableName type = value
C++用途廣泛些。開始學(xué)是有點(diǎn)難,入門就好了。我從開始學(xué)到能看懂一般C++用了一個(gè)來月,或許你比我聰明用的更少。最后想說的就是要堅(jiān)持,希望你成功。
1、Go(又稱 Golang)是 Google 的 Robert Griesemer,Rob Pike 及 Ken Thompson 開發(fā)的一種靜態(tài)強(qiáng)類型、編譯型語言。Go 語言語法與 C 相近,但功能上有:內(nèi)存安全,GC(垃圾回收),結(jié)構(gòu)形態(tài)及 CSP-style 并發(fā)計(jì)算。
2、go:v.去;走;(尤指與某人)去(某處或出席某項(xiàng)活動(dòng));移動(dòng),旅行,行走(指方式或距離)。n.(游戲或活動(dòng)中)輪到的機(jī)會(huì);(做某事的)嘗試,一番努力;精力;活力;熱情;干勁。
1、編譯vimgdb
下載vimgdb73和vim73
mkdir -p ./tmp
cd tmp
tar zxvf ../vim-7.3.tar.gz
unzip ../vimgdb-for-vim7.3-master.zip
mv vimgdb-for-vim7.3-master vimgdb-for-vim7.3
patch -p0 vimgdb-for-vim7.3/vim73.patch
cd vim73
安裝依賴
sudo apt-get install build-essential
sudo apt-get build-dep vim-gtk
sudo apt-get install libncurses5-dev
安裝
// 這里直接執(zhí)行make的操作
make
sudo make install
安裝vimgdb runtime
cd ../vimgdb-for-vim7.3
cp vimgdb_runtime ~/.vim/bundle
打開vim
:helptags ~/.vim/bundle/vimgdb_runtime/doc " 生成doc文件
添加配置.vimrc
" vimgdb插件
run macros/gdb_mappings.vim
在vim中執(zhí)行g(shù)db時(shí),報(bào) “Unable to read from GDB pseudo tty” 的錯(cuò)誤,因?yàn)闆]有安裝 gdb ,所以安裝gdb
sudo apt-get install gdb
2、安裝vundle
set up vundle
$ git clone ~/.vim/bundle/vundle
Configure Plugins
在.vimrc文件的開頭添加下面的內(nèi)容,有些不是必須的,可以注掉
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()
" alternatively, pass a path where Vundle should install plugins
"let path = '~/some/path/here'
"call vundle#rc(path)
" let Vundle manage Vundle, required
Plugin 'gmarik/vundle'
" The following are examples of different formats supported.
" Keep Plugin commands between here and filetype plugin indent on.
" scripts on GitHub repos
Plugin 'tpope/vim-fugitive'
Plugin 'Lokaltog/vim-easymotion'
Plugin 'tpope/vim-rails.git'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" scripts from
Plugin 'L9'
Plugin 'FuzzyFinder'
" scripts not on GitHub
Plugin 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
Plugin ''
" ...
filetype plugin indent on " required
" To ignore plugin indent changes, instead use:
"filetype plugin on
"
" Brief help
" : PluginList - list configured plugins
" : PluginInstall(!) - install (update) plugins
" : PluginSearch(!) foo - search (or refresh cache first) for foo
" : PluginClean(!) - confirm (or auto-approve) removal of unused plugins
"
" see :h vundle for more details or wiki for FAQ
" NOTE: comments after Plugin commands are not allowed.
" Put your stuff after this line
Install Plugins
Launch vim and run
: PluginInstall
vim +PluginInstall +qall
3、官方vim-lang插件
Config vim file .vimrc,Add content bellow in bottom of the file
" 官方的插件
" Some Linux distributions set filetype in /etc/vimrc.
" Clear filetype flags before changing runtimepath to force Vim to
" reload them.
filetype off
filetype plugin indent off
set runtimepath+=$GOROOT/misc/vim
filetype plugin indent on
syntax on
autocmd FileType go autocmd BufWritePre Fmt
4、代碼補(bǔ)全的插件gocode
配置go的環(huán)境變量,比如我的配置,GOPATH變量是必須要配置的,PATH中必須把GOPATH的bin也添加進(jìn)去,否則沒有自動(dòng)提示,會(huì)提示找不到模式
export GOROOT=/usr/local/go
export GOPATH=/data/app/gopath
export PATH=$PATH:$GOROOT/bin:$GOPATH/bin
Set up gocode
Then you need to get the appropriate version of the gocode, for 6g/8g/5g compiler you can do this:
go get -u github.com/nsf/gocode (-u flag for "update")
Configure vim in .vimrc file
Plugin 'nsf/gocode', {'rtp': 'vim/'}
Install Plugins
Launch vim and run
: PluginInstall
vim +PluginInstall +qall
寫一個(gè)helloword程序,輸入fmt后按C-xC-o如果能看到函數(shù)的聲明展示出來,說明安裝是正確的。
4、代碼跳轉(zhuǎn)提示godef
Set up godef
go get -v code.google.com/p/rog-go/exp/cmd/godef
go install -v code.google.com/p/rog-go/exp/cmd/godef
git clone ~/.vim/bundle/vim-godef
Configure vim in .vimrc file
Bundle 'dgryski/vim-godef'
Install Plugins
Launch vim and run
: PluginInstall
vim +PluginInstall +qall
5、代碼結(jié)構(gòu)提示gotags
Set up gotags
go get -u github.com/jstemmer/gotags
Put the following configuration in your vimrc:
Bundle 'majutsushi/tagbar'
nmap :TagbarToggle
let g:tagbar_type_go = {
\ 'ctagstype' : 'go',
\ 'kinds' : [
\ 'p:package',
\ 'i:imports:1',
\ 'c:constants',
\ 'v:variables',
\ 't:types',
\ 'n:interfaces',
\ 'w:fields',
\ 'e:embedded',
\ 'm:methods',
\ 'r:constructor',
\ 'f:functions'
\ ],
\ 'sro' : '.',
\ 'kind2scope' : {
\ 't' : 'ctype',
\ 'n' : 'ntype'
\ },
\ 'scope2kind' : {
\ 'ctype' : 't',
\ 'ntype' : 'n'
\ },
\ 'ctagsbin' : 'gotags',
\ 'ctagsargs' : '-sort -silent'
\ }
命令模式下按在右邊就會(huì)顯示當(dāng)前文件下的函數(shù)名,結(jié)構(gòu)體名等等,光標(biāo)放到相應(yīng)的tag上,按回車可以快速跳到程序中的相應(yīng)位置。
再次按會(huì)關(guān)閉tag窗口。
PS:本地的.vimrc的配置
" 插件管理器 vundle
set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/vundle/
call vundle#rc()
" alternatively, pass a path where Vundle should install plugins
"let path = '~/some/path/here'
"call vundle#rc(path)
" let Vundle manage Vundle, required
Plugin 'gmarik/vundle'
" The following are examples of different formats supported.
" Keep Plugin commands between here and filetype plugin indent on.
" scripts on GitHub repos
" Plugin 'tpope/vim-fugitive'
" Plugin 'Lokaltog/vim-easymotion'
" Plugin 'tpope/vim-rails.git'
" The sparkup vim script is in a subdirectory of this repo called vim.
" Pass the path to set the runtimepath properly.
" Plugin 'rstacruz/sparkup', {'rtp': 'vim/'}
" scripts from
" Plugin 'L9'
" Plugin 'FuzzyFinder'
" scripts not on GitHub
" Plugin 'git://git.wincent.com/command-t.git'
" git repos on your local machine (i.e. when working on your own plugin)
" Plugin ''
" ...
"
filetype plugin indent on " required
" To ignore plugin indent changes, instead use:
" filetype plugin on
"
" Brief help
" : PluginList - list configured plugins
" : PluginInstall(!) - install (update) plugins
" : PluginSearch(!) foo - search (or refresh cache first) for foo
" : PluginClean(!) - confirm (or auto-approve) removal of unused plugins
"
" see :h vundle for more details or wiki for FAQ
" NOTE: comments after Plugin commands are not allowed.
" Put your stuff after this line
syntax on
" ********************************************************************
" 這里省略了其它不相關(guān)的插件
" vimgdb插件
run macros/gdb_mappings.vim
" 官方的插件
" Some Linux distributions set filetype in /etc/vimrc.
" Clear filetype flags before changing runtimepath to force Vim to
" reload them.
filetype off
filetype plugin indent off
set runtimepath+=$GOROOT/misc/vim
filetype plugin indent on
syntax on
autocmd FileType go autocmd BufWritePre buffer Fmt
" 代碼補(bǔ)全的插件
Bundle 'Blackrush/vim-gocode'
" 代碼跳轉(zhuǎn)提示
Bundle 'dgryski/vim-godef'
" 代碼結(jié)構(gòu)提示
Bundle 'majutsushi/tagbar'
nmap F8 :TagbarToggleCR
let g:tagbar_type_go = {
\ 'ctagstype' : 'go',
\ 'kinds' : [
\ 'p:package',
\ 'i:imports:1',
\ 'c:constants',
\ 'v:variables',
\ 't:types',
\ 'n:interfaces',
\ 'w:fields',
\ 'e:embedded',
\ 'm:methods',
\ 'r:constructor',
\ 'f:functions'
\ ],
\ 'sro' : '.',
\ 'kind2scope' : {
\ 't' : 'ctype',
\ 'n' : 'ntype'
\ },
\ 'scope2kind' : {
\ 'ctype' : 't',
\ 'ntype' : 'n'
\ },
\ 'ctagsbin' : 'gotags',
\ 'ctagsargs' : '-sort -silent'
\ }
不下200種 可以在維基百科搜索List_of_programming_languages
百度貼不了wiki的地址,大概是壟斷吧
A+BAT
A+
A++
A# .NET
A# (Axiom)
A-0
ABAP
ABC
ABC ALGOL
ABLE
ABSET
ABSYS
ACC
Accent
ActionScript
Ace DASL
ACT-III
Ada
APL
AWK
B
BACI
Baja
BASIC
bc
bcompile
BCPL
BeanShell
BETA
Bigwig
Big Snake
Bistro
BLISS
Blitz Basic
Block And List Manipulation (BALM)
Blue - Rejected prototype for Ada
Blue
Boo
Bourne shell - a.k.a sh
Bourne-Again shell - see Bash
Boxx
BPEL - Business Process Execution Language
Brainfuck
BUGSYS
BuildProfessional
BYOND
C
C--
C-script
C++ - ISO/IEC 14882
C# - ISO/IEC 23270
C shell (csh)
Caché ObjectScript - See also Caché Basic
Caml
Cat
Cayenne
C-BOT
Cecil
Cesil
Cg
Ch interpreter (C/C++ interpreter Ch)
Chapel
CHAIN
Charity
Chef
Chey
CHILL
CHIP-8
chomski
Chrome
ChucK
Cilk
CICS
CL
Clarion
Clean
Clipper
CLIST - Programming language for online applications in the MVS TSO environment
CLU
CMS-2
COBOL - ISO/IEC 1989
CobolScript
Cobra
CODE
ColdFusion
COMAL
Common Intermediate Language (CIL)
Common Lisp
Component Pascal
COMIT - List or string processing language
Concurrent Clean
Constraint Handling Rules
CORAL66
Corn
CorVision
COWSEL
CPL
CSP
Csound
Cue
Curl
Curry
Cyclone
D
Dao
DASL - Distributed Application Specification Language
DASL - Datapoint's Advanced Systems Language
DarkBASIC
DarkBASIC Professional
Dataflex
Datalog
dBASE
dc
Deesel (formerly G)
Delphi
Dialect
DinkC
DCL
Dialog Manager
DIBOL
DL/I
Dream Maker
Dylan
Dynace
E
Ease
EASY
Easy PL/I
EASYTRIEVE PLUS
eC (Ecere C)
ECMAScript
eDeveloper
Edinburgh IMP
Einstein
Eiffel
Elan
elastiC
Elf
Emacs Lisp
EGL Programming Language (EGL)
Epigram
Erlang
Escapade - server-side programming
Esterel
Euclid
Euphoria
Euler
EXEC
EXEC2
F
F#
Factor
Fan
Felix
Ferite
F#
FL
FLOW-MATIC
FOCAL
FOCUS
FOIL
FORMAC
Formula language
Forth
Fortran - ISO/IEC 1539
Fortress
FoxPro
FP
Frag Script
Franz Lisp
Frink
Frontier
F-Script
Gambas
G-code
General Algebraic Modeling System
Generic Java
Gibiane
G (LabVIEW)
G?del
Godiva
GOTRAN (see IBM 1620)
GOTO++
GPSS
GraphTalk
GRASS
Green
Groovy
H - Business processing language from NCR.
HAL/S - Real-time aerospace programming language
HAScript
Haskell - An advanced functional programming language
HaXe - Open Source language which can compile to four different platforms, including PHP and Flash
HyperTalk
IBM Basic assembly language
IBM RPG
ICI
Icon
IDL
IMP
Inform
Information Processing Language (IPL)
Informix-4GL
Io
IPTSCRAE
Interactive System Productivity Facility
J
J#
J++
JADE
JAG
Jal
Janus
Java
JavaScript
Jim++
JCL
Join Java
JOSS
Joule
JOVIAL
Joy
JScript
JSP
J2EE
J2ME
K
KEE
Kiev
Korn Shell
KIF
Kite
Kogut
KRC
KRL
KRYPTON
L
LabVIEW
Lagoona
LANSA
Lasso
Lava
Leda
Lead
Leadwerks Script
Legoscript
Leopard
Lexico
Lfyre
Liberty BASIC
Limbo
Limnor
LINC
Lingo
Lisaac
Lisp - ISO/IEC 13816
Lite-C
Logo
LOLCODE
LPC
LSL
LSE
Lua
Lucid
Lush
Lustre
LYaPAS
LSL
M4
MAD
MADCAP
MAGIC - See eDeveloper
Magik
Magma
MapBasic
Maple
MAPPER (Unisys/Sperry) now part of BIS
M-A-R-E-K (Programming language)
MARK-IV (Sterling/Informatics) now VISION:BUILDER of CA
Mary
Mathematica
MATLAB
MATA
Maxima (see also Macsyma)
MaxScript internal language 3D Studio Max
Maya (MEL)
Multiprocessor C#
Mercury
Mesa
METAL
Michigan Algorithm Decoder see MAD programming language
Microcode
MicroScript
MillScript
MIMIC
Mindscript
Miranda
Miva
ML
Moby
MODCAP
Model 204 User Language
Modula
Modula-2
Modula-3
Mondrian
Mortran
Moto
MOUSE
MSIL - Deprecated name for Common Intermediate Language
MSL
MONO
MUMPS
Napier88
Natural
Nemerle
NESL
Net.Data
Neuralware
NewtonScript
NGL
Nial
NXT-G
Nice
Nickle
Nosica
NQC
Nu
o:XML
Oberon
Objective Modula-2
Object Lisp
ObjectLOGO
Object Pascal
Objective-C
Objective Caml
Obliq
Objectstar
ObjectView
Ocaml
occam
occam-π
Octave
OmniMark
Opal
Open programming language
OPS5
Organiser Programming Language (OPL) - cf. Psion Organiser
Oxygene
Oz
PARI/GP
Parser
Pascal - ISO 7185
Pawn
PBASIC
PCASTL
PEARL
Perl
Perl Data Language
PHP
Pico
Piet
Pike
PIKT
PILOT
Pizza
PL 11
PL/0
PL/8
PL/B
PL/C
PL/I - ISO 6160
PL/M
PL/P
PL/SQL
Plankalkül
PLD
PLEX
PLEXIL
Pliant
PNGlish
PPL
POP-11
Poplog
PORTRAN
PostScript
Ppc++
Processing
Prograph
Progress 4GL
Prolog
Turbo Prolog
Promela
Protheus
PRO-IV
Python
Q
Qi
QtScript
QuakeC
QPL
Quikcomp (for the Moonrobot XI)
R
R++ - Based on C++ and added semanteme description
Rascal
Ratfiv
Ratfor
RBScript
rc
REPL - Really Easy Programming Language
REBOL - Relative Expression Based Object Language
Red - Rejected prototype for Ada
Redcode
REDO
REFAL
Revolution
REXX
Rigal
Rlab
Robot Scripting Language (RSL)
RPG - Report Program Generator
RPL
RScript
Ruby
Russell Programming Language
REALBasic
S
S2
S-PLUS
S-Lang
SAIL
SAKO
SAM76
SAS
Sather
Scala
ScalPL
SCAR
SCATRAN
Scheme
Scilab
Script.NET
Sed
Seed7
Self
SETL
Shadow Programming Interface (Developing)
ShadowScript
Shift Script
SIGNAL
SiMPLE
SIMPOL
SIMSCRIPT
Simula
SISAL
Slate
SLIP
SMALL - SMALL Machine Algol Like Language
Small
Smalltalk
SNOBOL - String Oriented Symbolic Language
SPITBOL
Snowball
SPARK
Spice
SPIN
SP/k
SPL/1 - aka SPL/I
SPS (1620) - see IBM 1620
Squirrel
SR
SSL
Standard ML
StringLang
Subtext
SuperCollider
Suneido
SYMPL
SyncCharts
Synergy/DE
SystemVerilog
T
TACL
TACPOL
TagsMe
TADS
TIE
Transaction Application Language
Tcl
Transact-SQL
teco
TELCOMP
Telon
Tempo
thinBasic
Titanium
TI-Basic
Today
Tom
TOM
Topspeed - see Clarion
TorqueScript
tpu
Trac
Trine
TTCN
Turbo Pascal
Turing
TUTOR\
Tutorial D
TXL
Ubercode
Ultra 32
Unicon
Uniface
Unix shell
Unlambda
UnrealScript
Use
V
Vala
VDM++
VDM-SL
Verilog
VHDL
Visual Assembler
Visual Basic - Visual Beginners All-purpose Symbolic Instruction Code
Visual Basic .NET
Visual DataFlex
Visual DialogScript
Visual FoxPro
Visual J++
Visual Objects
VBScript
VX-REXX
Vvvv
Water
WATFOR - see WATFIV
WATFIV
WAXHTML
WebQL
Whitespace
Winbatch
WinDev
Windows PowerShell
X++
X10
Xbase++ 32Bit Windows language
XBL
xbScript - Also xBaseScript
xHarbour
XL
XOTcl
XPL
XPL0
XQuery
XSLT - See XPath
Y
YACC
YAFL
Yellow - Rejected prototype for Ada
Yorick
Y
Z++
Z notation - A program specification language, like UML.
Zonnon
ZOPL
ZPL